[英]Pandas Dataframe - replace NaN with 0 if column value condition
[英]Pandas: Replace dataframe column if it is `NaN`
我有一個包含很多列的數據框。 一欄可能含有NaN
。 在這種情況下,可以在下一列中找到該值。
為了簡化...在這里:
In[1]:
d = {'col1': [1, 2, 3],
'col2': [5, np.nan, np.nan],
'col3': [55, 9, 22]}
df = pd.DataFrame(data=d)
print(tabulate(df, headers = 'keys', tablefmt = 'psql'))
Out[1]:
+----+--------+--------+--------+
| | col1 | col2 | col3 |
|----+--------+--------+--------|
| 0 | 1 | 5 | 55 |
| 1 | 2 | nan | 9 |
| 2 | 3 | nan | 22 |
+----+--------+--------+--------+
應該在這里變成這個:
In[2]:
d = {'col1': [1, 2, 3],
'col2': [5, 9, 22],
'col3': [55, 9, 22]}
df = pd.DataFrame(data=d)
print(tabulate(df, headers = 'keys', tablefmt = 'psql'))
Out[2]:
+----+--------+--------+--------+
| | col1 | col2 | col3 |
|----+--------+--------+--------|
| 0 | 1 | 5 | 55 |
| 1 | 2 | 9 | <== 9 | # col3's value copied to col2
| 2 | 3 | 22 | <== 22 | # col3's value copied to col2
+----+--------+--------+--------+
我嘗試了這個(沒有成功):
df.loc[ df['col2'].isna() ] = df[ df['col2'].isna() ]['col3']
有什么建議嗎?
您需要按行向后填充:
df.bfill(axis=1)
# col1 col2 col3
#0 1.0 5.0 55.0
#1 2.0 9.0 9.0
#2 3.0 22.0 22.0
是的,您可以只使用np.where
df.col2=np.where(df.col2.isna(),df.col3,df.col2)
df
Out[535]:
col1 col2 col3
0 1 5.0 55
1 2 9.0 9
2 3 22.0 22
用於使用.loc
修復代碼
df.loc[ df['col2'].isna(),'col2' ] = df[ df['col2'].isna() ]['col3']
df
Out[538]:
col1 col2 col3
0 1 5.0 55
1 2 9.0 9
2 3 22.0 22
也,
d['col2'].fillna(d['col3'], inplace = True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.