简体   繁体   English

根据 Pandas 中的 id 将列值从一个数据帧复制到另一个数据帧

[英]Copy column value from one dataframe to another based on id in Pandas

I am trying to copy Name from df2 into df1 where ID is common between both dataframes.我正在尝试将Namedf2复制到df1 ,其中ID在两个数据帧之间是通用的。

df1: df1:

ID    Name 

1     A
2     B
4     C
16    D
7     E

df2: df2:

ID    Name 

1     X
2     Y
7     Z

Expected Output:预期输出:

ID    Name 

1     X
2     Y
4     C
16    D
7     Z

I have tried like this, but it didn't worked.我试过这样,但没有奏效。 I am not able to understand how to assign value here.我无法理解如何在这里赋值。 I am assigning =df2['Name'] which is wrong.我正在分配=df2['Name']这是错误的。

for i in df2["ID"].tolist():
    df1['Name'].loc[(df1['ID'] == i)] = df2['Name']

Try with update尝试update

df1 = df1.set_index('ID')
df1.update(df2.set_index('ID'))
df1 = df1.reset_index()
df1
Out[476]: 
   ID Name
0   1    X
1   2    Y
2   4    C
3  16    D
4   7    Z

如果行的顺序无关紧要,那么连接两个 dfs 和 drop_duplicates 将达到结果,

df2.append(df1).drop_duplicates(subset='ID')

another solution would be,另一种解决方案是,

s = df1["Name"]
df1.loc[:,"Name"]=df1["ID"].map(df2.set_index("ID")["Name"].to_dict()).fillna(s)

o/P:开/关:

   ID Name
0   1    X
1   2    Y
2   4    C
3  16    D
4   7    Z

One more for consideration再考虑一个

df,dg = df1,df2
df = df.set_index('ID')
dg = dg.set_index('ID')
df.loc[dg.index,:] = dg               # All columns
#df.loc[dg.index,'Name'] = dg.Name    # Single column
df = df.reset_index()

>>> df
   ID Name
0   1    X
1   2    Y
2   4    C
3  16    D
4   7    Z

Or for a single column (index for both is 'ID'或者对于单个列(两者的索引都是“ID”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据 Pandas 中的列值将内容从一个 Dataframe 复制到另一个 Dataframe - Copy contents from one Dataframe to another based on column values in Pandas pandas - 有没有办法根据条件将值从一个 dataframe 列复制到另一个列? - pandas - Is there a way to copy a value from one dataframe column to another based on a condition? 根据多列索引将值从一个 dataframe 复制到另一个 - Copy value from one dataframe to another based on multiple column index 根据条件将值从一列复制到另一列(使用熊猫) - Copy value from one column to another based on condition (using pandas) Pandas 基于非恒定值的第三列将值从一列复制到另一列 - Pandas copy value from one column to another based on a value third column that is not constant 使用基于 ID 列的另一行的值来估算 Pandas 数据框列 - Impute Pandas dataframe column with value from another row based on ID column 如何根据 Pandas 中的第三列将值从一列复制到另一列? - How to copy a value from one column to another based on a third column in Pandas? 根据另一个 dataframe 的 id 和值在一个 dataframe 上设置值 - Setting value on one dataframe based on the id and value from another dataframe Pandas 将列名从一个数据帧复制到另一个 - Pandas copy column names from one dataframe to another 根据 pandas dataframe 中的另一列从一列中获取值时返回空数组 - Empty array returned while fetching value from one column based on another column in pandas dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM