在 Pandas 中将两个系列组合成一个 DataFrame [英] Combining two Series into a DataFrame in pandas
本文介绍了在 Pandas 中将两个系列组合成一个 DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个系列 s1
和 s2
具有相同(非连续)索引.如何将 s1
和 s2
组合为 DataFrame 中的两列,并将其中一个索引保留为第三列?
I have two Series s1
and s2
with the same (non-consecutive) indices. How do I combine s1
and s2
to being two columns in a DataFrame and keep one of the indices as a third column?
推荐答案
我认为 concat
是一个很好的方法.如果它们存在,它使用系列的名称属性作为列(否则它只是给它们编号):
I think concat
is a nice way to do this. If they are present it uses the name attributes of the Series as the columns (otherwise it simply numbers them):
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 个以上的系列.
这篇关于在 Pandas 中将两个系列组合成一个 DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文