Series数据查看,重新索引,对齐,增加/修改/删除值
查看
s = pd.Series(np.random.rand(20))
# 默认查看前五个数
print(s.head())
# 默认查看后五个数
print(s.tail())
0 0.105106
1 0.983218
2 0.867018
3 0.523619
4 0.658780
dtype: float64
15 0.311551
16 0.597593
17 0.406730
18 0.842302
19 0.129568
重新索引
# 重新索引,按照新的索引排序,不存在时为Null,不是重命名
s1 = pd.Series(np.random.rand(5),index=list('abcde'))
print(s1)
s2 = s1.reindex(list('cdefg'))
print(s2)
# 不存在时用0补齐
s3 = s1.reindex(list('abehr'),fill_value=0)
print(s3)
a 0.399513
b 0.253803
c 0.675937
d 0.424185
e 0.816803
dtype: float64
c 0.675937
d 0.424185
e 0.816803
f NaN
g NaN
dtype: float64
a 0.399513
b 0.253803
e 0.816803
h 0.000000
r 0.000000
dtype: float64
对齐
s1 = pd.Series(np.random.rand(4)*10,index=['Tom','Jack','Lie','Tee'])
s2 = pd.Series(np.random.rand(4)*10,index=['Jack','Tee','Lie','Tom'])
print(s1)
print(s2)
print(s1+s2)
Tom 9.794435
Jack 2.112581
Lie 7.512132
Tee 4.234891
dtype: float64
Jack 3.447699
Tee 2.639847
Lie 4.062681
Tom 7.319619
dtype: float64
Jack 5.560279
Lie 11.574813
Tee 6.874739
Tom 17.114053
dtype: float64
添加
s= pd.Series(np.random.rand(5),index=list('abcde'))
print(s)
s['f']=3
print(s)
print('----------')
s1=pd.Series(np.random.rand(2),index=list('xy'))
print(s1)
s2=s.append(s1)
print(s2
a 0.486482
b 0.920532
c 0.051677
d 0.683919
e 0.215718
dtype: float64
a 0.486482
b 0.920532
c 0.051677
d 0.683919
e 0.215718
f 3.000000
dtype: float64
----------
x 0.317171
y 0.292308
dtype: float64
a 0.486482
b 0.920532
c 0.051677
d 0.683919
e 0.215718
f 3.000000
x 0.317171
y 0.292308
dtype: float64
删除
s= pd.Series(np.random.rand(5),index=list('abcde'))
print(s)
s1=s.drop('e')
print(s1)
a 0.220960
b 0.548689
c 0.915444
d 0.307031
e 0.266007
dtype: float64
a 0.220960
b 0.548689
c 0.915444
d 0.307031
dtype: float64
修改
s= pd.Series(np.random.rand(5),index=list('abcde'))
print(s)
s['a']=1000
print(s)
a 0.290346
b 0.118413
c 0.256721
d 0.556101
e 0.041743
dtype: float64
a 1000.000000
b 0.118413
c 0.256721
d 0.556101
e 0.041743
dtype: float64