0

例如我有这个:

df_1 = pd.DataFrame({'A': [3 for _ in xrange(10)],
                     'B': [3 for _ in xrange(10)],
                     'C': [3 for _ in xrange(10)]})
df_2 = pd.DataFrame({'A': [2 for _ in xrange(5)],
                     'B': [2 for _ in xrange(5)],
                     'C': [2 for _ in xrange(5)]})

print(df_1 - df_2)

和输出将如预期:

    A   B   C
0   1   1   1
1   1   1   1
2   1   1   1
3   1   1   1
4   1   1   1
5 NaN NaN NaN
6 NaN NaN NaN
7 NaN NaN NaN
8 NaN NaN NaN
9 NaN NaN NaN

如何用来自的值填充新创建的 DF 中的缺失值df_1

4

1 回答 1

4

您可以使用combine_first来填写缺失值:

In [2]: (df_1 - df_2).combine_first(df_1)
Out[2]:
   A  B  C
0  1  1  1
1  1  1  1
2  1  1  1
3  1  1  1
4  1  1  1
5  3  3  3
6  3  3  3
7  3  3  3
8  3  3  3
9  3  3  3
于 2013-03-17T23:56:05.860 回答