python-3.x - 屏蔽与另一组数据不相等的数据并存储结果

标签 python-3.x pandas dataframe

有谁知道如何修改“更改”数据框以仅评估真实的单元格?我只想将那些项目发送到 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,您可以将whereother 参数一起使用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/

相关文章:

python - 解析Python中的数学表达式

python - __main__ 是否保证始终可导入?

python - 对于不一致的日期范围,用零填充 pandas groupby

python - Pandas:汇总数据框中的所有元素?

python - 将列表中的字符串插入数据框公式以在 Pandas 中循环计算

python - Python 3.x 中是否有 while(input()) 循环

python - Pandas 中的 Rowwise

pandas - python Pandas : dataframe read rows (readlines)

r - 使用重复时忽略大小写

python - 计算字符串列之间的相关性