Pandas基本功能之算術運算、排序和排名
阿新 • • 發佈:2018-11-05
算術運算和資料對齊
Series和DataFrame中行運算和列運算有種特徵叫做廣播
在將物件相加時,如果存在不同的索引對,則結果的索引就是該索引對的並集。自動的資料對齊操作在不重疊的索引處引入了NA值,NA值在算術運算中過程中傳播。
import pandas as pd from pandas import Series import numpy as np s1 = Series([7.3,-2.5,3.4,1.5],index=['a','c','d','e']) s2 = Series([-2.1,3.6,-1.5,4,3.1],index=['a','c','e','f','g']) s1+s2 a 5.2 c 1.1 d NaN e 0.0 f NaN g NaN dtype: float64
對於DataFrame,對齊操作會同時發生在行和列上。
df1 = pd.DataFrame(np.arange(9.).reshape(3,3),columns=['b','c','d'],index=['ohio','texas','colorado']) df1 b c d ohio 0.0 1.0 2.0 texas 3.0 4.0 5.0 colorado6.0 7.0 8.0 df2 = pd.DataFrame(np.arange(12.).reshape(4,3),columns=['b','d','e'],index=['utah','ohio','texas','oregon']) df2 b d e utah 0.0 1.0 2.0 ohio 3.0 4.0 5.0 texas 6.0 7.0 8.0 oregon 9.0 10.0 11.0 df1+df2 b c d e coloradoNaN NaN NaN NaN ohio 3.0 NaN 6.0 NaN oregon NaN NaN NaN NaN texas 9.0 NaN 12.0 NaN utah NaN NaN NaN NaN
在算術方法中填充值
df1 = pd.DataFrame(np.arange(12.).reshape(3,4),columns=list('abcd')) df2 = pd.DataFrame(np.arange(20.).reshape(4,5),columns=list('abcde')) df1 a b c d 0 0.0 1.0 2.0 3.0 1 4.0 5.0 6.0 7.0 2 8.0 9.0 10.0 11.0 df2 a b c d e 0 0.0 1.0 2.0 3.0 4.0 1 5.0 6.0 7.0 8.0 9.0 2 10.0 11.0 12.0 13.0 14.0 3 15.0 16.0 17.0 18.0 19.0 df1+df2 a b c d e 0 0.0 2.0 4.0 6.0 NaN 1 9.0 11.0 13.0 15.0 NaN 2 18.0 20.0 22.0 24.0 NaN 3 NaN NaN NaN NaN NaN ### 這裡面的fill_value=0不是指填充0,而是填充的值為0加上以前的值 df1.add(df2,fill_value=0) a b c d e 0 0.0 2.0 4.0 6.0 4.0 1 9.0 11.0 13.0 15.0 9.0 2 18.0 20.0 22.0 24.0 14.0 3 15.0 16.0 17.0 18.0 19.0 ### 重新索引的時候,fill_value的值是填充1 df1.reindex(columns=df2.columns,fill_value=1) a b c d e 0 0.0 1.0 2.0 3.0 1 1 4.0 5.0 6.0 7.0 1 2 8.0 9.0 10.0 11.0 1
靈活的算術方法:
方法 | 說明 |
---|---|
add | + |
sub | - |
div | / |
mul | * |
DataFrame和Series之間的運算
這就叫做廣播,會傳遞下去的進行算術運算
arr = np.arange(12.).reshape(3,4)
arr
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
arr-arr[0]
array([[0., 0., 0., 0.],
[4., 4., 4., 4.],
[8., 8., 8., 8.]])
dataframe中
frame = pd.DataFrame(np.arange(12.).reshape(4,3),columns=list('bde'),index=['utah','ohio','texas','oregon'])
frame
b d e
utah 0.0 1.0 2.0
ohio 3.0 4.0 5.0
texas 6.0 7.0 8.0
oregon 9.0 10.0 11.0
# 先取utah行
series=frame.ix['utah']
b 0.0
d 1.0
e 2.0
Name: utah, dtype: float64
frame-series
b d e
utah 0.0 0.0 0.0
ohio 3.0 3.0 3.0
texas 6.0 6.0 6.0
oregon 9.0 9.0 9.0
#如果某個索引值在DataFrame的列或Series的索引中找不到,則參與運算的兩個物件就會被重新索引以形成並集。
series2 = Series(range(3),index=['b','e','f'])
series2
frame+series2
b d e f
utah 0.0 NaN 3.0 NaN
ohio 3.0 NaN 6.0 NaN
texas 6.0 NaN 9.0 NaN
oregon 9.0 NaN 12.0 NaN
# 如果你希望匹配列且在列上廣播,則必須使用算術運算方法,axis = 0 代表列索引,axis=1代表行索引。
series3 = frame['d']
utah 1.0
ohio 4.0
texas 7.0
oregon 10.0
Name: d, dtype: float64
frame.sub(series3, axis=0)
b d e
utah -1.0 0.0 1.0
ohio -1.0 0.0 1.0
texas -1.0 0.0 1.0
oregon -1.0 0.0 1.0
函式應用和對映
apply方法
frame = pd.DataFrame(np.arange(12.).reshape(4,3),columns = list('bde'),index=['utah','ohio','texas','oregon'])
frame
b d e
utah 0.0 1.0 2.0
ohio 3.0 4.0 5.0
texas 6.0 7.0 8.0
oregon 9.0 10.0 11.0
# 預設操作列
f = lambda x:x.max()-x.min()
frame.apply(f)
b 9.0
d 9.0
e 9.0
dtype: float64
# 指定操作行
frame.apply(f,axis=1)
utah 2.0
ohio 2.0
texas 2.0
oregon 2.0
dtype: float64
# 如果都實現不了你要的需求,可以直接寫函式
def f(x):
return Series([x.min(),x.max()],index=['min','max'])
frame.apply(f)
b d e
min 0.0 1.0 2.0
max 9.0 10.0 11.0
applymap方法
# 還可以python函式的佔位符使用,之所以叫applymap,是因為Series有一個應用於元素級函式的map方法
format = lambda x: '你好%s' % x
frame.applymap(format)
b d e
utah 你好0.0 你好1.0 你好2.0
ohio 你好3.0 你好4.0 你好5.0
texas 你好6.0 你好7.0 你好8.0
oregon 你好9.0 你好10.0 你好11.0
frame['d'].map(format)
utah 你好1.0
ohio 你好4.0
texas 你好7.0
oregon 你好10.0
Name: d, dtype: object
排序和排名
排序sort_index、sort_values
Series可以進行索引排序,預設進行升序,如果要降序排序,可以sort_index(ascending=False)
Series按值排序,sort_vlaues()
obj = Series(range(4),index=['d','c','a','b'])
obj
d 0
c 1
a 2
b 3
dtype: int64
obj.sort_index()
a 2
b 3
c 1
d 0
dtype: int64
obj.sort_index(ascending=False)
d 0
c 1
b 3
a 2
dtype: int64
obj.sort_values()
d 1
c 2
b 3
a 4
dtype: int64
# 降序
obj1.sort_values(ascending=False)
b 3
a 2
c 1
d 0
dtype: int64
# 在排序時,任何缺失值預設都會被放到Series的末尾
obj2 = Series([4,np.nan,7,np.nan,-2,1])
obj2.sort_values()
4 -2.0
5 1.0
0 4.0
2 7.0
1 NaN
3 NaN
dtype: float64
DataFrame可以進行索引排序,預設為行索引排序
frame=pd.DataFrame(np.arange(12).reshape(4,3),index=list('badc'),columns=[2,1,3])
frame
2 1 3
b 0 1 2
a 3 4 5
d 6 7 8
c 9 10 11
# 這裡的axis為列排序
frame.sort_index(axis=1)
1 2 3
b 1 0 2
a 4 3 5
d 7 6 8
c 10 9 11
frame.sort_index()
2 1 3
a 3 4 5
b 0 1 2
c 9 10 11
d 6 7 8
# 在DataFrame上,你可以將一個或多個列的名字傳遞給by選項即可達到目的。
frame1 = pd.DataFrame({'b':[4,7,-3,2],'a':[0,1,0,1]})
frame1
b a
0 4 0
1 7 1
2 -3 0
3 2 1
frame1.sort_index(by='b')
b a
2 -3 0
3 2 1
0 4 0
1 7 1
frame1.sort_index(by=['a','b'])
b a
2 -3 0
0 4 0
3 2 1
1 7 1
排名rank()
表示在這個數在原來的Series中排第幾名,有相同的數,取其排名平均(預設)作為值
在obj中,4和4的排名是第4名和第五名,取平均得4.5。7和7的排名分別是第六名和第七名,則其排名取平均得6.5
obj4 = Series([7,-5,7,4,2,0,4])
obj4.rank()
0 6.5
1 1.0
2 6.5
3 4.5
4 3.0
5 2.0
6 4.5
dtype: float64
# 根據值在源資料中出現的順序進行排名
obj4.rank(method='first')
0 6.0
1 1.0
2 7.0
3 4.0
4 3.0
5 2.0
6 5.0
dtype: float64