python dataframe merge 合并 列求和
时间: 2023-09-08 07:03:57 浏览: 173
在Python中,使用pandas库的DataFrame.merge()函数可以合并两个数据帧。首先,我们需要导入pandas库并读取要合并的两个数据帧。然后,指定要合并的列作为键,并选择合并方式。在合并完成后,我们可以使用DataFrame的sum()函数计算各列的和。
下面是一个示例代码:
```python
import pandas as pd
# 读取两个数据帧
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3'],
'C': [1, 2, 3, 4]})
df2 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
'D': [5, 6, 7, 8]})
# 合并数据帧
merged_df = pd.merge(df1, df2, on='A')
# 计算列的和
sum_result = merged_df.sum()
print(sum_result)
```
输出结果为:
```
A A0A1A2A3
B B0B1B2B3
C 10
D 26
dtype: object
```
上述代码首先定义了两个数据帧df1和df2,然后使用merge函数将它们合并为merged_df。最后,使用sum函数计算每列的总和,并将结果打印出来。在输出结果中,每列的和以列名为索引展示出来。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)