gpt4 book ai didi

python - 替换 Pandas 中跨列的重复值

转载 作者:太空狗 更新时间:2023-10-29 20:51:15 24 4
gpt4 key购买 nike

我有一个简单的数据框:

df = [    {'col1' : 'A', 'col2': 'B', 'col3':   'C', 'col4':'0'},
{'col1' : 'M', 'col2': '0', 'col3': 'M', 'col4':'0'},
{'col1' : 'B', 'col2': 'B', 'col3': '0', 'col4':'B'},
{'col1' : 'X', 'col2': '0', 'col3': 'Y', 'col4':'0'}
]
df = pd.DataFrame(df)
df = df[['col1', 'col2', 'col3', 'col4']]
df

看起来像这样:

| col1 | col2 | col3 | col4 |
|------|------|------|------|
| A | B | C | 0 |
| M | 0 | M | 0 |
| B | B | 0 | B |
| X | 0 | Y | 0 |

我只想在各行中用字符“0”替换重复的字符。它归结为保留我们遇到的第一个重复值,如下所示:

| col1 | col2 | col3 | col4 |
|------|------|------|------|
| A | B | C | 0 |
| M | 0 | 0 | 0 |
| B | 0 | 0 | 0 |
| X | 0 | Y | 0 |

这看起来很简单,但我被卡住了。任何朝着正确方向的插入将不胜感激。

最佳答案

您可以使用 duplicated 方法返回一个 bool 索引器,指示元素是否重复:

In [214]: pd.Series(['M', '0', 'M', '0']).duplicated()
Out[214]:
0 False
1 False
2 True
3 True
dtype: bool

然后您可以通过将其映射到数据框的各行来创建掩码,并使用 where 执行替换:

is_duplicate = df.apply(pd.Series.duplicated, axis=1)
df.where(~is_duplicate, 0)

col1 col2 col3 col4
0 A B C 0
1 M 0 0 0
2 B 0 0 0
3 X 0 Y 0

关于python - 替换 Pandas 中跨列的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39907315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com