如何结合两个索引不同的 pandas 系列? [英] How to combine two pandas series which are differently indexed?

查看:68
本文介绍了如何结合两个索引不同的 pandas 系列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将两个索引不同的系列组合在一起(相同的行数).我尝试了pd.concat((s1, s2), axis=1). 例如,s1是:

I try to combine two differently indexed series together (same number of rows). I tried pd.concat((s1, s2), axis=1). For example, s1 is:

index | s1
----- | -----
0     | 1.5
----- | -----
1     | 2

和s2是:

index | s2
----- | -----
a     | 1
----- | -----
b     | 2

但是我得到了

index | s1  | s2  
----- | --- | --- 
0     | 1.5 | NaN
----- | --- | ---
1     | 2   | NaN
----- | --- | ---
a     | NaN | 1
----- | --- | ---
b     | NaN | 2

我想要的是:

index | s1  | s2 
----- | --- | ---
a     | 1.5 | 1
----- | --- | ---
b     | 2   | 2

即保留series2的索引. 我怎么能得到这个?非常感谢!

That is keep the index of series2. How could I get this? Many thanks!

推荐答案

首先通过s2索引设置s1的索引:

Set index of s1 by s2 index first:

s1.index = s2.index
df = pd.concat([s1, s2], axis=1)
print (df)
    s1  s2
a  1.5   1
b  2.0   2

这篇关于如何结合两个索引不同的 pandas 系列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆