1 import pandas as pd
2 import numpy as np
3
4 s = pd.Series([1,3,5,6,8],index=list('acefh'))
5 s.index # 读取行索引
6 # 输出 Index(['a', 'c', 'e', 'f', 'h'], dtype='object')
7
8 s.reindex(list('abcdefgh')) # 索引再定义,与元索引相同,值不变,其它变为NaN
9 s.reindex(list('abcdefgh'),fill_value=0) # 将其它的索引设置默认值0
10 s.reindex(list('abcdefgh'), method='ffill')
11 # 其它元Series没有的索引的值对应上一行已有的索引对应值
12
13 df = pd.DataFrame(np.random.randn(4,6),index=list('ADFH'),columns=['one','two','three','four','five','six'])
14 df2 = df.reindex(index=list('ABCDEFGH'))
15 # DataFrame中再定义行索引,新的索引将默认赋值NaN
16
17 df.reindex(index=list('ABCDEFGH'),fill_value=0) # DataFrame中为新的索引赋值0
18 df.loc['A']['one'] = 100 # 将‘A'行’one‘列赋值100
19
20 df.reindex(columns=['one','three','five','seven'],fill_value=0)
21
22 df.reindex(index=list('ABCDEFGH'),method='ffill') # method只对列有效果
23 # method='ffill',找到上面一行的对应列的值 赋值给新添加的行
24 # 但是df没有改变 但是df没有改变 但是df没有改变 但是df没有改变 但是df没有改变
25
26 df.drop('A') # 默认按行
27 df.drop(['two','four'],axis=1) #按列
28 # 但是df没有改变 但是df没有改变 但是df没有改变 但是df没有改变 但是df没有改变
29
30 df = pd.DataFrame(np.arange(12).reshape(4,3),index=['one','two','three','four'],columns=list('ABC'))
31
32 df.apply(lambda x: x.max()-x.min()) # 按列
33 df.apply(lambda x: x.max()-x.min(), axis=1) # 按行
34
35
36 def min_max(x):
37 return pd.Series([x.min(),x.max()],index=['min','max']) # 按行
38 df.apply(min_max, axis=1)
39
40 df = pd.DataFrame(np.random.randn(4,3),index=['one','two','three','four'],columns=list('ABC'))
41
42
43 # formater = lambda x: '%.03f' % x
44 formater = '{0:0.3f}'.format # 两个结果相同,取3位有效数字
45
46 df = pd.DataFrame(np.random.randint(1,10,(4,3)),index=list('ABCD'),columns=['one','two','three'])
47
48 df.sort_values(by='two',ascending=False) 通过by找到主要排序列对象 ascending=False按从大到小排列
49
50 s = pd.Series([3,6,2,6,4])
51
52 s.rank(method='average')
53 # 默认,rank表示列中的值对应的大小排位号(小的数排位靠前)
54 # df未改变 df未改变 df未改变 df未改变 df未改变 df未改变
55
56 df.rank(method='first') # 按列取排位号(小的数排位靠前)
57 s = pd.Series(list('abbcdabacad'))
58 s.value_counts() # 列中相应的值出现的次数
59 s.unique() # 找出列中所有不重复的值
60 s.isin(['a','c','d']) # 判断列中的值在['a','c','d']是否有相同的值
61 s.isin(s.unique()) # 判断列中的值在array(['a', 'b', 'c', 'd'])是否有相同的值