gpt4 book ai didi

python - 在 Pandas 中连接两个数据框的行

转载 作者:IT老高 更新时间:2023-10-28 20:33:02 25 4
gpt4 key购买 nike

我需要连接两个数据帧 df_adf_b 具有相等的行数(nRow),而不考虑键。该功能类似于R编程语言中的cbind。每个数据框中的列数可能不同。

生成的数据帧将具有相同的行数 nRow 和列数等于两个数据帧中列数的总和。换句话说,这是两个数据帧的盲列连接。

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)

最佳答案

调用 concat并传递参数 axis=1 以按列连接:

In [5]:

pd.concat([df_a,df_b], axis=1)
Out[5]:
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

merging, joining and concatenating 的各种方法都有一个有用的指南在线。

例如,由于您没有冲突的列,您可以 merge并使用索引,因为它们具有相同的行数:

In [6]:

df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
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

出于与上述相同的原因,一个简单的 join也可以:

In [7]:

df_a.join(df_b)
Out[7]:
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

关于python - 在 Pandas 中连接两个数据框的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28135436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com