pandas.DataFrame.combine_first#
- DataFrame.combine_first(other)[源代码]#
使用 other 中相同位置的值更新 null 元素。
通过用另一个 DataFrame 中的非空值填充一个 DataFrame 中的空值来组合两个 DataFrame 对象。结果 DataFrame 的行和列索引将是两者的并集。在调用 first.combine_first(second) 后,结果 DataFrame 包含 ‘first’ DataFrame 的值,并在 first.loc[index, col] 和 second.loc[index, col] 都不为缺失值时覆盖 second 的值。
- Parameters:
- otherDataFrame
用于填充空值的提供的 DataFrame。
- Returns:
- DataFrame
组合提供的 DataFrame 与其他对象的結果。
参见
DataFrame.combine使用给定的函数在两个 DataFrame 上执行逐 Series 的操作。
Examples
>>> df1 = pd.DataFrame({'A': [None, 0], 'B': [None, 4]}) >>> df2 = pd.DataFrame({'A': [1, 1], 'B': [3, 3]}) >>> df1.combine_first(df2) A B 0 1.0 3.0 1 0.0 4.0
如果该空值的位置在 other 中不存在,则空值仍然存在。
>>> df1 = pd.DataFrame({'A': [None, 0], 'B': [4, None]}) >>> df2 = pd.DataFrame({'B': [3, 3], 'C': [1, 1]}, index=[1, 2]) >>> df1.combine_first(df2) A B C 0 NaN 4.0 NaN 1 0.0 3.0 1.0 2 NaN 3.0 1.0