[英]Pandas missing values using conditions (groupby other columns)
我有一個這樣的數據框
df
Col A Col B Col C
25 1 2
NaN 3 1
27 2 3
29 3 1
我想根據 Col C 和 Col B 填充 col A 中的 Nan 值。
我的輸出 df 應該是這樣的
25 1 2
29 3 1
27 2 3
29 3 1
我試過這個代碼df.groupby(['Col B','Col C']).ffill()
但沒有用。任何建議都會有所幫助
干得好:
df['Col A'] = df["Col A"].fillna(df.groupby(['Col B','Col C'])["Col A"].transform(lambda x: x.mean()))
print(df)
印刷:
Col A Col B Col C
0 25.0 1 2
1 29.0 3 1
2 27.0 2 3
3 29.0 3 1
你可以試試
df.fillna(df.groupby(['ColB','ColC']).transform('first'),inplace=True)
df
Out[386]:
ColA ColB ColC
0 25.0 1 2
1 29.0 3 1
2 27.0 2 3
3 29.0 3 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.