考慮到與值替換楠如下:大熊貓多指標的行和列:從匹配的行
import pandas as pd
import numpy as np
df=pd.DataFrame({'County':['A','B','A','B','A','B','A','B','A','B'],
'Hospital':['a','b','e','f','i','j','m','n','b','r'],
'Enrollment':[44,55,95,54,81,54,89,76,1,67],
'Year':['2012','2012','2012','2012','2012','2013',
'2013','2013','2013','2013']})
d2=pd.pivot_table(df,index=['County','Hospital'],columns=['Year'])#.sort_columns
d2
Enrollment
Year 2012 2013
County Hospital
A a 44.0 NaN
b NaN 1.0
e 95.0 NaN
i 81.0 NaN
m NaN 89.0
B b 55.0 NaN
f 54.0 NaN
j NaN 54.0
n NaN 76.0
r NaN 67.0
如果醫院如「B」存在一次以上,它有前一年沒有數據(第一次出現'b'),我想爲其他行('b')分配上一年的註冊值,並刪除第一年不包含數據的'b'行:
Enrollment
Year 2012 2013
County Hospital
A a 44.0 NaN
b 55.0 1.0
e 95.0 NaN
i 81.0 NaN
m NaN 89.0
B f 54.0 NaN
j NaN 54.0
n NaN 76.0
r NaN 67.0
到目前爲止,我可以識別重複行並刪除,但我只是堅持用值w替換NaN這裏需要:
d2=d2.reset_index()
d2['dup']=d2.duplicated('Hospital',keep=False)
標誌,刪除,複製醫院沒有數據的最近年份:
Hospital=d2.columns.levels[0][1]
Y1=d2.columns.levels[1][0]
Y2=d2.columns.levels[1][1]
d2['Delete']=np.nan
d2.loc[(pd.isnull(d2.Enrollment[Y2]))&(d2['dup']==True),'Delete']='Yes'
重置索引後,找出重複的醫院
保留除刪除行外的所有行:
d2=d2.loc[d2['Delete']!='Yes']
關閉,但醫院行保留的標準是基於哪一方缺乏第一年的數據,並且有第二年的數據(滿足這兩個標準的那一個是保留的數據)。 –