在熊猫中连接两个数据框的行
- 2025-01-15 08:45:00
- admin 原创
- 92
问题描述:
我需要水平连接两个具有相同行数()的数据框df_a
和,而不考虑任何键。此功能类似于R 编程语言中的。每个数据框中的列数可能不同。df_b
`nRow`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)
解决方案 1:
调用concat
并传递参数axis=1
来按列连接:
In [5]:
pd.concat([df_a,df_b], axis=1)
Out[5]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \n0 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
网上有一个关于合并、连接和串联的各种方法的有用指南。
例如,由于没有冲突的列,因此您可以merge
使用索引,因为它们具有相同的行数:
In [6]:
df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \n0 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 \n0 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
解决方案 2:
感谢@EdChum,我也遇到了同样的问题,尤其是当索引不匹配时。不幸的是,在 Pandas 指南中没有提到这种情况(例如,当你删除一些行时)
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)
解决方案 3:
如果索引标签不同(例如,如果df_a.index == [0, 1, 2]
和df_b.index == [10, 20, 30]
为True
),则直接join
(或concat
或merge
)可能会产生 NaN 行。在这种情况下,一种有用的方法是set_axis()
强制索引相同。
concatenated_df = df_a.join(df_b.set_axis(df_a.index))
# or
concatenated_df = pd.concat([df_a, df_b.set_axis(df_a.index)], axis=1)
如果帧的长度相同,那么您也可以将其分配df_b
给df_a
。与concat
(或join
或merge
)不同,这会改变df_a
并且不会创建新的数据帧。
df_a[df_b.columns] = df_b
# if index labels are different
df_a[df_b.columns] = df_b.set_axis(df_a.index)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD