如何在 Pandas 中合并两个行数相等的 DataFrame?

Barbara Streisand
发布: 2024-10-26 19:40:03
原创
333 人浏览过

How to Combine Two DataFrames with Equal Number of Rows in Pandas?

连接 Pandas 中两个数据帧的行

水平连接两个数据帧 df_a 和 df_b,行数相等,而不考虑键,使用 concat 函数并将 axis 参数设置为 1:

<code class="python">pd.concat([df_a, df_b], axis=1)</code>
登录后复制
登录后复制

例如,考虑以下两个数据帧:

<code class="python">dict_data = {'Treatment': ['C', 'C', 'C'], 'Biorep': ['A', 'A', 'A'], 'Techrep': [1, 1, 1], 'AAseq': ['ELVISLIVES', 'ELVISLIVES', 'ELVISLIVES'], 'mz':[500.0, 500.5, 501.0]}
df_a = pd.DataFrame(dict_data)
dict_data = {'Treatment1': ['C', 'C', 'C'], 'Biorep1': ['A', 'A', 'A'], 'Techrep1': [1, 1, 1], 'AAseq1': ['ELVISLIVES', 'ELVISLIVES', 'ELVISLIVES'], 'inte1':[1100.0, 1050.0, 1010.0]}
df_b = pd.DataFrame(dict_data)</code>
登录后复制

使用 axis=1 的 concat 函数,我们可以按列连接这些数据帧:

<code class="python">pd.concat([df_a, df_b], axis=1)</code>
登录后复制
登录后复制

这将产生一个具有相同行数 (3) 且列数等于两个数据帧中列数之和 (9) 的数据帧:

        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  
登录后复制

请注意,由于没有重叠的列,合并后的数据框直接将列组合成一个表。

此外,您可以使用它们的索引来合并数据框,因为它们有相同的行数,提供相同的结果:

<code class="python">df_a.merge(df_b, left_index=True, right_index=True)</code>
登录后复制

以上是如何在 Pandas 中合并两个行数相等的 DataFrame?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!