![](/img/trans.png)
[英]pandas Dataframe Replace NaN values with with previous value based on a key column
[英]How to fill NaN cells in a pandas dataframe, based on the previous column?
我有以下 DF
col1| col2
123| NaN
234| 234
456| NaN
567| 567
我想要做的是,如果右側單元格為空,則將左側單元格復制到右側單元格,因此輸出為
col1| col2
123| 123
234| 234
456| 456
567| 567
我試圖用fillna做一些事情,但失敗了
按列使用ffill
,因此axis=1
:
df = df.ffill(axis=1)
print (df)
col1 col2
0 123.0 123.0
1 234.0 234.0
2 456.0 456.0
3 567.0 567.0
df.fillna(method='ffill',axis=1)
您可以使用numpy
包中的np.where
假設您的數據框稱為df
:
import numpy as np
df['col2'] = np.where(df['col2'].isnull(),df['col1'],df['col2'])
這會給你:
col1| col2
123| 123
234| 234
456| 456
567| 567
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.