我有兩個資料框:主要和輔助。我將輔助連接到主要。它導致 NaN 在幾行中,我想填充它們,而不是全部。代碼:
df1 = pd.DataFrame({'Main':[00,10,20,30,40,50,60,70,80]})
df1 =
Main
0 0
1 10
2 20
3 30
4 40
5 50
6 60
7 70
8 80
df2 = pd.DataFrame({'aux':['aa','aa','bb','bb']},index=[0,2,5,7])
df2 =
aux
0 aa
2 aa
5 bb
7 bb
df = pd.concat([df1,df2],axis=1)
# After concating, in the aux column, I want to fill the NaN rows in between
# the rows with same value. Example, fill rows between 0 and 2 with 'aa', 2 and 5 NaN, 5 and 7 with 'bb'
df = pd.concat([df1,df2],axis=1).fillna(method='ffill')
print(df)
目前結果:
Main aux
0 0 aa
1 10 aa
2 20 aa
3 30 aa # Wrong, here it should be NaN
4 40 aa # Wrong, here it should be NaN
5 50 bb
6 60 bb
7 70 bb
8 80 bb # Wrong, here it should be NaN
預期結果:
Main aux
0 0 aa
1 10 aa
2 20 aa
3 30 NaN
4 40 NaN
5 50 bb
6 60 bb
7 70 bb
8 80 NaN
uj5u.com熱心網友回復:
如果我理解正確,你想要的可以這樣完成。您想要填充回填和前向填充給出相同值的 NaN。
ff = df.aux.fillna(method='ffill')
bf = df.aux.fillna(method='bfill')
df.aux = ff[ff == bf]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/478450.html
下一篇:檢查快速輸入?
