简体   繁体   English

并排连接两个数据框

[英]Join two data-frames side by side

I have two data frames that I want to join side by side.我有两个要并排加入的数据框。

They have the same number of rows and I want them next to eachother so I can then total the resulting rows.它们具有相同的行数,我希望它们彼此相邻,这样我就可以汇总结果行。

So I tried to join using pd.concat所以我尝试使用 pd.concat 加入

df1 = pd.DataFrame(data.iloc[34:55, 1:19])

df2 = pd.DataFrame(data.iloc[91:112, 1:19])

df3 = pd.concat([df1, df2], axis=1)

This joins the two data frames one on top of the other and changes 0's to NaN这将两个数据帧一个接一个地连接起来,并将 0 更改为 NaN

I tried merging but with no success either.我尝试合并但也没有成功。

Apologies if very basic, I have researched the problem but am very much a beginner.抱歉,如果非常基本,我已经研究过这个问题,但我还是个初学者。

Thanks谢谢

Here is one of the data frames, extracted from an excel spreadhseet这是从 excel spreadhseet 中提取的数据帧之一

Say I have the following dataframes;假设我有以下数据框;

df1=pd.DataFrame({'a':[1,2,3,4,5,6], 'b':[6,7,8,9,9,0],'c':[6,7,8,9,9,0],'d':[6,7,8,9,9,0],'e':[6,7,8,9,9,0]})
df2=pd.DataFrame({'a':[1,2,13,41,5,6], 'b':[61,7,83,9,9,60],'c':[61,7,83,9,9,60],'d':[61,7,83,9,9,60],'e':[61,7,83,9,9,60]})

Set a common index(You must be careful though, make sure you set an index common among the datframes.In this case, I just reset them to make it start from 0 on wards)设置一个通用索引(你必须小心,确保你设置了一个在数据帧中通用的索引。在这种情况下,我只是将它们重置为从 0 开始)

df1= df.iloc[0:3, 1:3]
df1.reset_index(drop=True, inplace=True)
df2=df.iloc[3:6, 1:3]
df2.reset_index(drop=True, inplace=True)

Do an inner concat做一个内部连接

result = pd.concat([df1, df2], axis=1, join='inner')
result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM