用另一个具有相同列名和长度的数据框的值替换列中的值

时间:2019-01-11 08:35:22

标签: python pandas replace

我有两个具有相同列名,相同长度的相同数据框,我想用相同的列名替换另一列中的一列中的值

df1
Name total 
a     6
a     7
b     8
c     100
c     232

df2
Name total 
a     12
a     0
b     1002
c     2
c     1  

df1['total'] = df2['total']
df1.loc[df1.Name.isin(df2.Name), 'total'] = df2['total']

s = df2['total'] and tried with
s = df2.set_index('total')
df1['total'] = df1['total'].replace(s)

我一直在列中获取NaN值

我的预期输出是

df1
Name total 
a     12
a     0
b     1002
c     2
c     1

1 个答案:

答案 0 :(得分:0)

df1['total'] = df2['total']正常工作。试用以下代码:

import pandas as pd
df1 = pd.DataFrame([['a',6],['a',7],['b',8],['c',100],['c',232]], columns = ['Name', 'total'])
df2 = pd.DataFrame([['a',12],['a',0],['b',1002],['c',2],['c',1]], columns = ['Name', 'total'])

df1['total'] = df2['total']

希望这会有所帮助。