我有一个关于 Pandas 以及正确索引和替换值的问题。
我有 2 个数据帧,df1 和 df2,具有相同的列(Col1、Col2、Col3 和 Col4)。
df1 = pd.DataFrame([['A','b','x',1], ['A','b','y',2], ['A','c','z',3], ['B','b','x',4]], columns=['Col1', 'Col2', 'Col3', 'Col4'])
df2 = pd.DataFrame([['A','b','y',0], ['B','b','x',0]], columns=['Col1','Col2','Col3','Col4'])
df1
Col1 Col2 Col3 Col4
0 A b x 1
1 A b y 2
2 A c z 3
3 B b x 4
df2
Col1 Col2 Col3 Col4
0 A b y 0
1 B b x 0
在DF1,我想替换值COL4中匹配的值,该行的其他列在(Col1中,col2的和COL3)DF2与另一个值(假设100)。
生成的 df1 将如下所示:
df1
Col1 Col2 Col3 Col4
0 A b x 1
1 A b y 100
2 A c z 3
3 B b x 100
我试过这样的事情:
columns = list(df1.columns)
columns.remove('Col4')
df1.loc[(df1[cols] == df2[cols].values).all(axis=1)]['Col4']=100
但是我遇到了错误,我不确定这是否达到了我想要的。
您可以isin
对索引进行操作,并通过布尔掩码分配值:
cols = ['Col1', 'Col2', 'Col3']
temp1 = df1.set_index(cols)
temp2 = df2.set_index(cols)
# get the booleans here
booleans = temp1.index.isin(temp2.index)
# this assigns 100 to only rows in Col4
# that are True
df1.loc[booleans, 'Col4'] = 100
df1
Col1 Col2 Col3 Col4
0 A b x 1
1 A b y 100
2 A c z 3
3 B b x 100
或者,您可以使用pd.merge
和indicator
参数解决它:
(df1.merge(df2,
on = cols,
how = 'left',
indicator=True,
suffixes = (None, '_y'))
.assign(Col4 = lambda df: np.where(df._merge == 'both',
100,
df.Col4))
.loc[:, df1.columns]
)
Col1 Col2 Col3 Col4
0 A b x 1
1 A b y 100
2 A c z 3
3 B b x 100
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句