Python 连接熊猫中两个数据帧的行
我需要将两个数据帧Python 连接熊猫中两个数据帧的行,python,pandas,dataframe,Python,Pandas,Dataframe,我需要将两个数据帧df_a和df_b一个接一个地连接起来,它们具有相同的行数(nRow),而不考虑任何键。此函数类似于R编程语言中的cbind。每个数据帧中的列数可能不同 结果数据帧将具有相同的行数nRow,列数等于两个数据帧中的列数之和。换句话说,这是两个数据帧的盲列连接 import pandas as pd dict_data = {'Treatment': ['C', 'C', 'C'], 'Biorep': ['A', 'A', 'A'], 'Techrep': [1, 1, 1],
df_a
和df_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)
调用并传递paramaxis=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
有一个有用的指南,介绍各种在线学习方法
例如,由于没有冲突列,因此可以使用索引,因为它们具有相同的行数:
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
出于与上述相同的原因,一个简单的方法也适用:
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
感谢@EdChum
我也遇到了同样的问题,尤其是当索引不匹配时。不幸的是,在pandas guide中,这种情况没有出现(例如,当您删除一些行时)
import pandas as pd
t=pd.DataFrame()
t['a']=[1,2,3,4]
t=t.loc[t['a']>1] #now index starts from 1
u=pd.DataFrame()
u['b']=[1,2,3] #index starts from 0
#option 1
#keep index of t
u.index = t.index
#option 2
#index of t starts from 0
t.reset_index(drop=True, inplace=True)
#now concat will keep number of rows
r=pd.concat([t,u], axis=1)