Pandas DataFrame.combine(~) 方法组合了两个 DataFrame 的列。请注意,只有共享相同列标签的列才会被合并。
参数
1. other | DataFrame
您想要与之组合的DataFrame。
2. func | function
该函数接受两个参数:第一个 DataFrame 中的一列和第二个 DataFrame 中要组合的列,两者均为类型 Series 。此函数的返回值必须是代表结果列的Series。
3. fill_value | scalar | optional
将填充缺失值实例的值 (NaN)。填充发生在合并过程之前。默认情况下,fill_value=None 。
4. overwrite | boolean | optional
布尔值的含义如下:
| 值 | 说明 | 
|---|---|
| 
 | 如果一个 DataFrame 中的列在另一个 DataFrame 中不存在,则合并列的条目将填充为  | 
| 
 | 如果源 DataFrame 中的列在其他 DataFrame 中不存在,则该列将出现在合并的 DataFrame 中,并且其条目保持不变。 然而,反之则不然。如果另一个 DataFrame 具有源 DataFrame 中不存在的列,那么这些列也将出现在最终的 DataFrame 中,但其条目填充为  | 
默认情况下,overwrite=True 。请参阅下面的示例以进行说明。
返回值
DataFrame,其列根据参数组合。
例子
基本用法
考虑以下数据帧:
df = pd.DataFrame({"A":[3,4], "B":[5,6]})
df_other = pd.DataFrame({"A":[1,8], "B":[2,9]})
   A  B   |      A  B
0  3  5   |   0  1  2
1  4  6   |   1  8  9合并两个 DataFrames 的列以仅保留较高的值:
df.combine(df_other, np.maximum)
   A  B
0  3  5
1  8  9自定义函数
我们还可以为 func 传入自定义函数:
def foo(col, col_other):   # a pair of Series
 return col + col_other
df.combine(df_other, foo)
   A   B
0  4   7
1  12  15请注意以下事项:
- 
foo只是计算并返回两个 DataFrame 中一对匹配列的总和。
- 
foo在这里被调用两次,因为有两对匹配的列标签。
指定覆盖
考虑以下列标签不匹配的DataFrames:
df = pd.DataFrame({"A":[3,4], "B":[5,6]})
df_other = pd.DataFrame({"A":[1,8], "C":[2,9]})
   A  B   |      A  C
0  3  5   |   0  1  2
1  4  6   |   1  8  9默认情况下, overwrite=True ,这意味着其他 DataFrame 中不存在的列将用 NaN 填充,反之亦然:
df.combine(df_other, np.maximum)
   A  B    C
0  3  NaN  NaN
1  8  NaN  NaN这里,列B和C是NaN,因为df没有列C,而df_other没有列B。
我们可以通过设置 overwrite=False 来保持源 DataFrame 的列完整:
df.combine(df_other, np.maximum, overwrite=False)
   A  B  C
0  3  5  NaN
1  8  6  NaN在这里,请注意 C 列(仅出现在 df_other 中的列)的条目仍然由 NaN 填充。
相关用法
- Python Pandas DataFrame combine_first方法用法及代码示例
- Python Pandas DataFrame copy方法用法及代码示例
- Python PySpark DataFrame collect方法用法及代码示例
- Python PySpark DataFrame coalesce方法用法及代码示例
- Python Pandas DataFrame corrwith方法用法及代码示例
- Python PySpark DataFrame corr方法用法及代码示例
- Python Pandas DataFrame convert_dtypes方法用法及代码示例
- Python Pandas DataFrame columns属性用法及代码示例
- Python PySpark DataFrame cov方法用法及代码示例
- Python Pandas DataFrame count方法用法及代码示例
- Python PySpark DataFrame colRegex方法用法及代码示例
- Python PySpark DataFrame columns属性用法及代码示例
- Python PySpark DataFrame count方法用法及代码示例
- Python Pandas DataFrame corr方法用法及代码示例
- Python Pandas DataFrame cov方法用法及代码示例
- Python Pandas DataFrame clip方法用法及代码示例
- Python Pandas DataFrame cummax方法用法及代码示例
- Python Pandas DataFrame cumprod方法用法及代码示例
- Python Pandas DataFrame cummin方法用法及代码示例
- Python Pandas DataFrame cumsum方法用法及代码示例
- Python Pandas DataFrame empty属性用法及代码示例
- Python Pandas DataFrame pop方法用法及代码示例
- Python Pandas DataFrame nsmallest方法用法及代码示例
- Python Pandas DataFrame sample方法用法及代码示例
- Python Pandas DataFrame items方法用法及代码示例
注:本文由纯净天空筛选整理自Isshin Inada大神的英文原创作品 Pandas DataFrame | combine method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
