python - 同时替换 pandas df 中的多个值

标签 python pandas replace

我正在尝试同时替换 pandas df 中的值。看起来该函数连续执行此操作,因此我替换的值最终被覆盖。使用下面的 X == Left,我想替换 A-DB-CC-B D-A。如果我只执行其中一个调用,效果会很好,但当我执行所有四个调用时,它就不行了。以下是我的尝试:

import pandas as pd

df = pd.DataFrame({   
    'X' : ['Left','Left','Left','Left','Right','Right','Right','Right'],
    'Y' : ['A','B','C','D','A','B','C','D'],            
    })

尝试 1:

df[(df['X'] == 'Left') & (df['Y'] == 'A')] = df['Y'].map({'A': 'D'})
df[(df['X'] == 'Left') & (df['Y'] == 'B')] = df['Y'].map({'B': 'C'})
df[(df['X'] == 'Left') & (df['Y'] == 'C')] = df['Y'].map({'C': 'B'})
df[(df['X'] == 'Left') & (df['Y'] == 'D')] = df['Y'].map({'D': 'A'})

输出:

       X  Y
0      D  D
1      C  C
2      B  B
3      A  A
4  Right  A
5  Right  B
6  Right  C
7  Right  D

尝试 2:

df.loc[(df['X'] == 'Left') & (df['Y'] == 'A'), 'Y'] = 'D'
df.loc[(df['X'] == 'Left') & (df['Y'] == 'B'), 'Y'] = 'C'
df.loc[(df['X'] == 'Left') & (df['Y'] == 'C'), 'Y'] = 'B'
df.loc[(df['X'] == 'Left') & (df['Y'] == 'D'), 'Y'] = 'A'

输出:

       X  Y
0   Left  A
1   Left  B
2   Left  B
3   Left  A
4  Right  A
5  Right  B
6  Right  C
7  Right  D

预期输出:

       X  Y
0   Left  D
1   Left  C
2   Left  B
3   Left  A
4  Right  A
5  Right  B
6  Right  C
7  Right  D

最佳答案

替换一次:

df.Y.update(df.loc[df['X'] == 'Left','Y'].replace({'A': 'D','B': 'C','C': 'B','D': 'A'}))
df
       X  Y
0   Left  D
1   Left  C
2   Left  B
3   Left  A
4  Right  A
5  Right  B
6  Right  C
7  Right  D

关于python - 同时替换 pandas df 中的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61378187/

相关文章:

python - Pandas:读取 CSV:ValueError:无法将字符串转换为 float

python - 如何清除缓存的查询?

python - 如何在某个未知索引处对字符串输入进行切片

python - 将新的字典值列添加到 pandas 数据框中

python - 在python中用非字符串值替换子字符串

javascript - AngularJS - 如果包含字符串,则删除 ng-repeat 项

python - 使用字典和 Replace() 函数替换字符串中的单词时出现的问题

python - 将一列拆分为多列,计数频率: 'int' object is not iterable

python - Selenium 错误 - ConnectionResetError : [WinError 10054] An existing connection was forcibly closed by the remote host

python - 在 Pandas (Python 3) 中用 0 替换空白