Python 当dataframe有多个同名列时,合并失败
这是本文的后续内容 我试图在一个公共列上合并两个dataframe,但一个dataframe有多个同名列。我想使用该列进行合并 这些是我的数据帧:Python 当dataframe有多个同名列时,合并失败,python,pandas,Python,Pandas,这是本文的后续内容 我试图在一个公共列上合并两个dataframe,但一个dataframe有多个同名列。我想使用该列进行合并 这些是我的数据帧: df1=pd.DataFrame(['abc',xyz',['abc',xyz',['xyz','abc']],columns=['max_speed','min_speed'])) df2=pd.DataFrame(['abc',xyz',['abc',xyz',['xyz',abc']],列=['max_speed','max_speed']))
df1=pd.DataFrame(['abc',xyz',['abc',xyz',['xyz','abc']],columns=['max_speed','min_speed']))
df2=pd.DataFrame(['abc',xyz',['abc',xyz',['xyz',abc']],列=['max_speed','max_speed']))
我有一个特例,其中我的dataframe有多个同名的列()
我尝试使用列的位置而不是列的名称来访问,但没有成功
我尝试的是:
df3=df1.merge(df2,右上=df1.columns[0],左上=df2.columns[0])
错误:
ValueError:列标签“max_speed”不唯一
请告诉我如何解决此问题。您可以
将列设置在df2
中所需的位置,然后使用合并和右\u index=True
print (df1.merge(df2.set_index(df2.iloc[:,0])
.iloc[:, 1:], #to select only the other column max_speed
left_on='max_speed', right_index=True,
suffixes=('','_'))
)
max_speed min_speed max_speed_
0 abc xyz xyz
0 abc xyz xyz
1 abc xyz xyz
1 abc xyz xyz
2 xyz abc abc
我可以只保留第一列max\u speed
吗?基本上,我在其他df中有超过10-15个max_speed列。所以最后只有一个max_速度就好了。@MurtazaHaji不知道你想要什么。事实上已经有两列同名,这是不直观的。我的理解是,在iloc中,它可以是.iloc[:,1:2]
,只保留df2中的另一列max_speed,或者只选择合并结果中的前N列,其中N是df1中的列数