有谁知道如何修改“更改”数据框以仅评估正确的单元格?我只想将这些项目发送到 df2 中的更改,从 df1 到更改数据框。这将替换所有单元格,我不能单独使用“掩码”,因为它是多维的。谢谢!
import pandas as pd
import numpy as np
df1=pd.DataFrame({'Col1' : ['blue', 2, 3, 4], 'Col2' : [90, 99, 3, 97], 'Col3' : [11, 12, 13, 14]})
df2=pd.DataFrame({'Col1' : ['blue', 2, 6], 'Col2' : [90, 99, 99], 'Col3' : [11, 12, 13]})
mask=df2.ne(df1)
#Line in question
changes=(df1.loc[mask.index].astype(str) + ' changed to: ***' + df2.loc[mask.index].astype(str)).fillna(df2.astype(str))
我希望输出看起来像:
Col1 Col2 Col3
0 blue 90 11
1 2 99 12
2 3 changed to: ***6 3 changed to: ***99.0 13
3 4 changed to: ***nan 97 changed to: ***nan 14 changed to: ***nan
最佳答案
IIUC,您可以将 where
与 other
参数 see docs 一起使用:
df1.where(df1.eq(df2), changes)
输出:
Col1 Col2 Col3
0 blue 90 11
1 2 99 12
2 3 changed to: ***6 3 changed to: ***99.0 13
3 4 changed to: ***nan 97 changed to: ***nan 14 changed to: ***nan
关于python-3.x - 屏蔽与另一组数据不相等的数据并存储结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48410104/