pandas 列绑定(绑定)两个数据帧 [英] Pandas column bind (cbind) two data frames

查看:65
本文介绍了 pandas 列绑定(绑定)两个数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ID为ID的数据框df_a:

I've got a dataframe df_a with id information:

    unique_id lacet_number 
15    5570613  TLA-0138365 
24    5025490  EMP-0138757 
36    4354431  DXN-0025343 

和另一个数据框df_b,具有与我知道的相同数量的行,它们对应于df_a中的行:

and another dataframe df_b, with the same number of rows that I know correspond to the rows in df_a:

     latitude  longitude 
0  -93.193560  31.217029  
1  -93.948082  35.360874  
2 -103.131508  37.787609  

我想做的就是将两者绑定在一起并得到:

What I want to do is simply cbind the two and get:

    unique_id lacet_number      latitude  longitude 
0     5570613  TLA-0138365    -93.193560  31.217029  
1     5025490  EMP-0138757    -93.948082  35.360874  
2     4354431  DXN-0025343   -103.131508  37.787609  

我尝试过的事情:

df_c = pd.concat([df_a, df_b], axis=1)

这给了我一个外部的连接.

which gives me an outer join.

    unique_id lacet_number    latitude  longitude
0         NaN          NaN  -93.193560  31.217029
1         NaN          NaN  -93.948082  35.360874
2         NaN          NaN -103.131508  37.787609
15    5570613  TLA-0138365         NaN        NaN
24    5025490  EMP-0138757         NaN        NaN
36    4354431  DXN-0025343         NaN        NaN

问题是两个数据帧的索引不匹配.我阅读了pandas.concat的文档,并看到有一个选项"ignore_index".但这仅适用于串联轴,在我的情况下是列,这当然不是我的正确选择.所以我的问题是:有没有简单的方法来实现这一目标?

The problem is that the indices for the two dataframes do not match. I read the documentation for pandas.concat, and saw that there is an option "ignore_index". But that only applies to the concatenation axis, in my case the columns and it certainly is not the right choice for me. So my question is: is there a simple way to achieve this?

推荐答案

如果您确定索引行的值相同,则为避免索引对齐顺序,只需调用

If you're sure the index row values are the same then to avoid the index alignment order then just call reset_index(), this will reset your index values back to start from 0:

df_c = pd.concat([df_a.reset_index(drop=True), df_b], axis=1)

这篇关于 pandas 列绑定(绑定)两个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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