Pandas Series 类似表格中的一个列(column),类似于一维数组,可以保存任何数据类型。
Series 由索引(index)和列组成,函数如下:
pandas.Series( data, index, dtype, name, copy)
参数说明:
data:一组数据(ndarray 类型)。
index:数据索引标签,如果不指定,默认从 0 开始。
dtype:数据类型,默认会自己判断。
name:设置名称。
copy:拷贝数据,默认为 False。
#!/usr/bin/python
import pandas as pd
aaa = pd.Series([1,2,3,4])
bbb = pd.Series([1,2,3,4], index = ['a','b','c','d'])
print(aaa)
print(type(aaa))
print(bbb)
输出:
0 1
1 2
2 3
3 4
dtype: int64
<class 'pandas.core.series.Series'>
a 1
b 2
c 3
d 4
dtype: int64
Series相当于一个列的一维数组,可以指定索引名称,也可根据索引名称获取相应的值。
可以使用.index,.values获取Series索引和数值信息:
#!/usr/bin/python
import pandas as pd
bbb = pd.Series([1,2,3,4], index = ['a','b','c','d'])
print(bbb.index)
print(bbb.values)
输出:
Index(['a', 'b', 'c', 'd'], dtype='object')
[1 2 3 4]
根据索引获取value:
#!/usr/bin/python
import pandas as pd
bbb = pd.Series([1,2,3,4], index = ['a','b','c','d'])
print(bbb[['a','b']])
out:
a 1
b 2
dtype: int64
注意索引也要以列表的形式出现。
通过条件,过滤一些数据,只需要加判断条件就好:
#!/usr/bin/python
import pandas as pd
bbb = pd.Series([1,2,3,4], index = ['a','b','c','d'])
print(bbb[bbb>2])
out:
c 3
d 4
dtype: int64
也可以直接做数据计算:
#!/usr/bin/python
import pandas as pd
bbb = pd.Series([1,2,3,4], index = ['a','b','c','d'])
print(bbb*2)
out:
a 2
b 4
c 6
d 8
dtype: int64
也可以做数据相加:
#!/usr/bin/python
import pandas as pd
aaa = {"name":"zhangsan", "age":25}
obj = pd.Series(aaa)
bbb = {"name":"lisi", "age":20, "height":170}
obj2 = pd.Series(bbb)
print(obj + obj2)
out:
age 45
height NaN
name zhangsanlisi
dtype: object
#判断是否有空值
print(obj3.isnull())
out:
age False
height True
name False
dtype: bool
#添加索引名
#!/usr/bin/python
import pandas as pd
aaa = {"name":"lisi", "age":20, "height":170}
obj = pd.Series(aaa)
obj.index.name = "info:"
print(obj)
out:
info:
name lisi
age 20
height 170
dtype: object
#Series对象名
#!/usr/bin/python
import pandas as pd
aaa = {"name":"lisi", "age":20, "height":170}
obj = pd.Series(aaa)
obj.index.name = "info:"
obj.name="李四"
print(obj)
out:
info:
name lisi
age 20
height 170
Name: 李四, dtype: object
参考: