Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于数据框中的id将列值从一个数据框复制到另一个数据框_Python_Python 3.x_Pandas_Dataframe - Fatal编程技术网

Python 基于数据框中的id将列值从一个数据框复制到另一个数据框

Python 基于数据框中的id将列值从一个数据框复制到另一个数据框,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,我正在尝试将Name从df2复制到df1中,其中ID在两个数据帧之间是通用的 df1: df2: 预期产出: ID Name 1 X 2 Y 4 C 16 D 7 Z 我试过这样做,但没有成功。我无法理解如何在这里赋值。我正在分配=df2['Name'],这是错误的 for i in df2["ID"].tolist(): df1['Name'].loc[(df1['ID'] == i)] = df2['Name']

我正在尝试将
Name
df2
复制到
df1
中,其中
ID
在两个数据帧之间是通用的

df1:

df2:

预期产出:

ID    Name 

1     X
2     Y
4     C
16    D
7     Z
我试过这样做,但没有成功。我无法理解如何在这里赋值。我正在分配
=df2['Name']
,这是错误的

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

尝试更新
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

尝试更新
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并删除重复项将获得结果

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

如果行的顺序无关紧要,则连接两个dfs并删除重复项将获得结果

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

另一个解决办法是

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


另一个解决办法是

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


还有一个供考虑

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

或者对于单个列(两个列的索引都是'ID'

请再考虑一个

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

或者对于单个列(二者的索引都是'ID'

@ben-yo谢谢,它正在工作,但是你知道为什么它将
int
列转换为
float
?@Rajnishkumar将要更新的列有一些
NaN
,这比我的
df.loc
分配解决方案快。这是因为
update
将索引与之对齐吗?@wwwii是的,reindex_像~@ben-yo谢谢,它正在工作,但是你知道为什么它会将
int
列转换为
float
?@Rajnishkumar由于更新会有一些
NaN
这比我的
df.loc
分配解决方案快。这是因为
update
将索引与之对齐吗?@wwwii是的,reindex\u like~我没有设置“ID”作为索引,“ID”列我没有将“ID”设置为索引,“ID”列