如何根据上一列在 pandas 数据框中填充 NaN 单元格?
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
您可以使用 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
df.fillna(method='ffill',axis=1)
我有以下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
您可以使用 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
df.fillna(method='ffill',axis=1)