Python 用不同的Dataframe替换列
我有两个数据帧,即'df'和'df1'Python 用不同的Dataframe替换列,python,pandas,dataframe,Python,Pandas,Dataframe,我有两个数据帧,即'df'和'df1' df Out[14]: first country Rating 0 Robert US 100 1 Chris Aus 99 2 Scarlett US 100 df1 Out[17]: last Role 0 Downey IronMan 1 Hemsworth Thor 2 Johansson B
df
Out[14]:
first country Rating
0 Robert US 100
1 Chris Aus 99
2 Scarlett US 100
df1
Out[17]:
last Role
0 Downey IronMan
1 Hemsworth Thor
2 Johansson BlackWidow
预期产出:
first last Role Rating
0 Robert Downey IronMan 100
1 Chris Hemsworth Thor 99
2 Scarlett Johansson BlackWidow 100
我需要删除“country”列并替换为另一个数据帧(即“df1”)
我知道,我可以加入数据帧并删除“国家”列,但我需要的列的顺序正好如此。IIUC:
new_df = df.merge(df1, on='Role').drop('country', axis=1)
new_df = new_df[['first', 'last', 'Role', 'Rating']]
你能试一试吗
df1.join(df2,lsuffix=''',rsuffix='r_')[[“第一”、“最后”、“角色”、“评级”]]
输出:
first last Role Rating
0 Robert Downey IronMan 100
1 Chris Hemsworth Thor 99
2 Scarlett Johansson BlackWidow 100
@摩哈迈德,您可以尝试以下方法: df2=pd.concat([df,df1],轴=1) df2=df2[[‘第一’、‘最后’、‘角色’、‘评级’]]
df2.head()在连接柱后是否尝试重新设置柱的范围?另外,当你加入他们时,输出是什么?我有没有办法不显式地给出列名就可以这样做?谢谢Balaji!它起作用了。。但是有没有办法在不明确提及列名的情况下获得它呢?。如果我能通过切片什么的,那就太好了。。很难提及大型数据集的所有列名..您不能使用
df.columns.tolist()
从数据帧的列名中获取最终的列列表吗?