如何合并Pandas系列并添加公共值

2024-05-12 18:35:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个Pandas系列(pandas.core.series.Series),我想把它们合并成一个系列,在公共键上添加如下值:

series1:
AAA Championship Car season                                       1
Act of Parliament of Ontario                                      1
Act of Parliament of the United Kingdom                          18
Act of Parliament of the United Kingdom election law              1

+

series2:
ATP Buenos Aires                                                  1
ATP World Tour Finals                                             1
Act of Parliament of British Columbia                             1
Act of Parliament of the United Kingdom                          18
Act of Parliament of the United Kingdom election law              1

=

series3:
AAA Championship Car season                                       1
ATP Buenos Aires                                                  1
ATP World Tour Finals                                             1
Act of Parliament of British Columbia                             1
Act of Parliament of Ontario                                      1
Act of Parliament of the United Kingdom                          36
Act of Parliament of the United Kingdom election law              2

Tags: ofthecaractunitedkingdomseasonaaa
3条回答

让我们试试pd.concatsum

series3 = pd.concat([series1,series2]).sum(level=0)

输出:

0
AAA Championship Car season                              1
ATP Buenos Aires                                         1
ATP World Tour Finals                                    1
Act of Parliament of British Columbia                    1
Act of Parliament of Ontario                             1
Act of Parliament of the United Kingdom                 36
Act of Parliament of the United Kingdom election law     2
Name: 1, dtype: int64

您可以使用pandas.Series.sum()https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.add.html 这也提供了一种填充缺失值的方法。你知道吗

例如,您的代码可以是

series3 = series1.add(series2, fill_value=0)
full_df = (
    pd.concat([series1, series2], axis = 0)
      .groupby(level=0)
      .sum()
)

相关问题 更多 >