Series常用函数
Series序列的创建及索引的创建
不带索引创建序列
obj = Series([4, 7, -5, 3])
print(obj)
-----------
0 4
1 7
2 -5
3 3
dtype: int64
获取序列的值和索引
print(obj.values)
print(obj.index)
-----------
[ 4 7 -5 3]
RangeIndex(start=0, stop=4, step=1)
另外添加索引
obj.index = ['Bob', 'Steve', 'Jeff', 'Ryan']
print(obj)
-----------
Bob 4
Steve 7
Jeff -5
Ryan 3
dtype: int64
创建带索引的序列
带index参数创建序列可以自定义索引
obj2 = Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])
-----------
d 4
b 7
a -5
c 3
dtype: int64
再来检查一下索引
print(obj2.index)
-----------
Index(['d', 'b', 'a', 'c'], dtype='object')
Series序列的基本操作
使用索引访问值、赋值
print(obj2['a'])
obj2['d'] = 6
print(obj2[['c', 'a', 'd']])
-----------
3
c 3
a -5
d 6
dtype: int64
按条件访问值
print(obj2[obj2 > 0])
-----------
d 6
b 7
c 3
dtype: int64
直接对序列进行运算,会影响整个序列
print(obj2*2)
-----------
d 12
b 14
a -10
c 6
dtype: int64
判断索引是否在序列中存在
print('a' in obj2)
-----------
True
用字典创建序列,会自动生成索引(字典的key)
sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000}
obj4 = Series(sdata)
print(obj4)
-----------
Ohio 35000
Texas 71000
Oregon 16000
Utah 5000
dtype: int64
判断序列中是否存在空值
print(obj4.isnull())
-----------
Ohio False
Texas False
Oregon False
Utah False
dtype: bool
两个序列相加,如果两个序列存在不同的索引,那么两个序列单独拥有的索引的值将被清空为NaN,其他共有的索引的值相加
sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'aaa': 5000}
obj5 = Series(sdata)
print(obj4 + obj5)
-----------
Ohio 70000.0
Oregon 32000.0
Texas 142000.0
Utah NaN
aaa NaN
dtype: float64
排序
序列按索引和值排序
obj4.sort_index(ascending=True) # ascending是否升序排
print(obj4)
obj4.sort_values(ascending=True)
print(obj4)
-----------
state
Ohio 35000
Texas 71000
Oregon 16000
Utah 5000
Name: population, dtype: int64
state
Ohio 35000
Texas 71000
Oregon 16000
Utah 5000
Name: population, dtype: int64