gpt4 book ai didi

python - 在 Pandas 中将两个系列组合成一个DataFrame

转载 作者:IT老高 更新时间:2023-10-28 12:12:18 30 4
gpt4 key购买 nike

我有两个系列 s1s2 具有相同(非连续)索引。如何将 s1s2 组合为 DataFrame 中的两列,并将其中一个索引保留为第三列?

最佳答案

我认为 concat是一个很好的方法来做到这一点。如果它们存在,它将使用 Series 的 name 属性作为列(否则它只是对它们进行编号):

In [1]: s1 = pd.Series([1, 2], index=['A', 'B'], name='s1')

In [2]: s2 = pd.Series([3, 4], index=['A', 'B'], name='s2')

In [3]: pd.concat([s1, s2], axis=1)
Out[3]:
s1 s2
A 1 3
B 2 4

In [4]: pd.concat([s1, s2], axis=1).reset_index()
Out[4]:
index s1 s2
0 A 1 3
1 B 2 4

注意:这扩展到超过 2 个系列。

关于python - 在 Pandas 中将两个系列组合成一个DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18062135/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com