【课程2.4】 Pandas数据结构Series:基本技巧
数据查看 / 重新索引 / 对齐 / 添加、修改、删除值
1.数据查看
s = pd.Series(np.random.rand(50))
print(s.head(10))
print(s.tail())
# .head()查看头部数据
# .tail()查看尾部数据
# 默认查看5条
-----------------------------------------------------------------------
0 0.730540
1 0.116711
2 0.787693
3 0.969764
4 0.324540
5 0.061827
6 0.377060
7 0.820383
8 0.964477
9 0.451936
dtype: float64
45 0.899540
46 0.237008
47 0.298762
48 0.848487
49 0.829858
dtype: float64
2.重新索引reindex
重新索引并不是给索引重命名,它类似于根据重新的索引排序
# .reindex将会根据索引重新排序,如果当前索引不存在,则引入缺失值
s = pd.Series(np.random.rand(3), index = ['a','b','c'])
print(s)
s1 = s.reindex(['c','b','a','d'])
print(s1)
# .reindex()中也是写列表
# 这里'd'索引不存在,所以值为NaN
s2 = s.reindex(['c','b','a','d'], fill_value = 0)
print(s2)
# fill_value参数:填充缺失值的值
-----------------------------------------------------------------------
a 0.343718
b 0.322228
c 0.746720
dtype: float64
c 0.746720
b 0.322228
a 0.343718
d NaN
dtype: float64
c 0.746720
b 0.322228
a 0.343718
d 0.000000
dtype: float64
3.Series对齐
s1 = pd.Series(np.random.rand(3), index = ['Jack','Marry','Tom'])
s2 = pd.Series(np.random.rand(3), index = ['Wang','Jack','Marry'])
print(s1)
print(s2)
print(s1+s2)
# Series 和 ndarray 之间的主要区别是,Series 上的操作会根据标签自动对齐
# index顺序不会影响数值计算,以标签来计算
# 空值和任何值计算结果扔为空值
-----------------------------------------------------------------------
Jack 0.753732
Marry 0.180223
Tom 0.283704
dtype: float64
Wang 0.309128
Jack 0.533997
Marry 0.626126
dtype: float64
Jack 1.287729
Marry 0.806349
Tom NaN
Wang NaN
dtype: float64
4.删除:.drop
s = pd.Series(np.random.rand(5), index = list('ngjur'))
print(s)
s1 = s.drop('n')
s2 = s.drop(['g','j'])
print(s1)
print(s2)
print(s)
# drop 删除元素之后返回副本(inplace=False)
-----------------------------------------------------------------------
n 0.876587
g 0.594053
j 0.628232
u 0.360634
r 0.454483
dtype: float64
g 0.594053
j 0.628232
u 0.360634
r 0.454483
dtype: float64
n 0.876587
u 0.360634
r 0.454483
dtype: float64
n 0.876587
g 0.594053
j 0.628232
u 0.360634
r 0.454483
dtype: float64
5.添加,三种添加方式
s1 = pd.Series(np.random.rand(5))
s2 = pd.Series(np.random.rand(5), index = list('ngjur'))
print(s1)
print(s2)
s1[5] = 100
s2['a'] = 100
print(s1)
print(s2)
print('-----')
# 直接通过下标索引/标签index添加值
s3 = s1.append(s2)
print(s3)
print(s1)
# 通过.append方法,直接添加一个数组
# .append方法生成一个新的数组,不改变之前的数组
-----------------------------------------------------------------------
6.修改
s = pd.Series(np.random.rand(3), index = ['a','b','c'])
print(s)
s['a'] = 100
s[['b','c']] = 200
print(s)
# 通过索引直接修改,类似序列
-----------------------------------------------------------------------
a 0.873604
b 0.244707
c 0.888685
dtype: float64
a 100.0
b 200.0
c 200.0
dtype: float64