gpt4 book ai didi

python - 删除一行 Pandas 数据框中的重复值

转载 作者:太空宇宙 更新时间:2023-11-03 13:32:50 25 4
gpt4 key购买 nike

我有一个 Pandas 数据框:

>>df_freq = pd.DataFrame([["Z11", "Z11", "X11"], ["Y11","",""], ["Z11","Z11",""]], columns=list('ABC'))

>>df_freq
A B C
0 Z11 Z11 X11
1 Y11
2 Z11 Z11

我想确保每一行都只有唯一值。因此它应该变成这样:删除的值可以用零或空替换

    A   B   C
0 Z11 0 X11
1 Y11
2 Z11 0

我的数据框很大,有数百列和数千行。目标是计算该数据框中的唯一值。我通过使用将数据框转换为矩阵并应用

来做到这一点
>>np.unique(mat.astype(str), return_counts=True)

但是在某些行中出现相同的值,我想在应用 np.unique() 方法之前删除它。我想在每一行中保留唯一值。

最佳答案

结合使用 astype(bool)duplicated

mask = df_freq.apply(pd.Series.duplicated, 1) & df_freq.astype(bool)

df_freq.mask(mask, 0)

A B C
0 Z11 0 X11
1 Y11
2 Z11 0

关于python - 删除一行 Pandas 数据框中的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43898903/

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