我有两个数据框,我想用== left(DF1)的方式用键(X)上的其他数据框替换空值。非常感谢。
DF1
X | Y
1 | a
2 | NaN
3 | c
DF2
X | Y
1 | a
2 | b
3 | NaN
4 | d
OUTPUT
X | Y
1 | a
2 | b
3 | c
答案 0 :(得分:1)
df1['Y'] = df1['X'].map(df2.set_index('X')['Y']).fillna(df1['Y'])
或将np.where
用作:
df1['Y'] = np.where(df1.Y.isnull(),df1['X'].map(df2.set_index('X')['Y']),df1['Y'])
print(df1)
X Y
0 1 a
1 2 b
2 3 c
答案 1 :(得分:1)
您可以根据df2的行创建一个字典,并将该字典与fillna结合使用:
import numpy as np
import pandas as pd
da1 = [[1, 'a'],
[2, np.nan],
[3, 'c']]
df1 = pd.DataFrame(data=da1, columns=['X', 'Y'])
da2 = [[1, 'a'],
[2, 'b'],
[3, np.nan],
[4, 'd']]
df2 = pd.DataFrame(data=da2, columns=['X', 'Y'])
mapping = dict(zip(df2.X, df2.Y))
df1.Y = df1.Y.fillna(df1.X.map(mapping))
print(df1)
输出
X Y
0 1 a
1 2 b
2 3 c