如何在 Python 中水平(按列)组合两个 Pandas DataFrame,类似于 R 中的'cbind”函数?

Barbara Streisand
发布: 2024-10-27 08:35:03
原创
563 人浏览过

How can I combine two Pandas DataFrames horizontally (column-wise) in Python, similar to the `cbind` function in R?

连接 Pandas 中两个数据帧的行

问题:
如何在 Python 中水平(按列)组合两个数据帧Pandas 库,类似于 R 中的 cbind 函数?

解决方案:
要水平连接数据帧而不考虑键,请使用带有 axis=1 参数的 pd.concat() 函数。此参数指定沿列的串联:

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

示例:
考虑以下示例:

<code class="python">import pandas as pd

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)

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

print(result)</code>
登录后复制

输出:

        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  
登录后复制

如您所见,生成的数据帧的行数和列数与两个原始数据帧的总和相同。

替代方法:
除了 pd.concat() 之外,还可以使用 merge() 或 join() 进行盲列连接。但是,这些方法需要数据帧之间匹配索引或键:

<code class="python"># Using merge()
result = df_a.merge(df_b, left_index=True, right_index=True)

# Using join()
result = df_a.join(df_b)</code>
登录后复制

以上是如何在 Python 中水平(按列)组合两个 Pandas DataFrame,类似于 R 中的'cbind”函数?的详细内容。更多信息请关注PHP中文网其他相关文章!

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