我認爲最好的理解pivoting
是小樣本中:
import pandas as pd
import numpy as np
countryKPI = pd.DataFrame({'germanCName':['a','a','b','c','c'],
'indicator.id':['z','x','z','y','m'],
'value':[7,8,9,7,8]})
print (countryKPI)
germanCName indicator.id value
0 a z 7
1 a x 8
2 b z 9
3 c y 7
4 c m 8
print (pd.pivot_table(countryKPI, index=['germanCName'], columns=['indicator.id']))
value
indicator.id m x y z
germanCName
a NaN 8.0 NaN 7.0
b NaN NaN NaN 9.0
c 8.0 NaN 7.0 NaN
如果需要更換NaN
到0
附加參數fill_value
:
print (countryKPI.pivot_table(index='germanCName',
columns='indicator.id',
values='value',
fill_value=0))
indicator.id m x y z
germanCName
a 0 8 0 7
b 0 0 0 9
c 8 0 7 0
事實上,這個例子是好的。但我怎樣才能防止NaN值? –
好的,你需要什麼? 'NaN'替換爲'0'? – jezrael
我看到所以問題是,在我的一些國家的數據並不是所有的指標都被報道...... :( –