python - Pandas,根据其他列值删除重复行

标签 python pandas

示例数据:

df1 = pd.DataFrame({
    'file': ['file1','file1','file1','file2','file2','file2','file3','file3','file3'],
    'prop1': ['True','False','True','False','False','False','True','False','False'],
    'prop2': ['False','False','False','False','True','False','False','True','False'],
    'prop3': ['False','True','False','True','False','True','False','False','True']
})

file    prop1   prop2   prop3
0   file1   True    False   False
1   file1   False   False   True
2   file1   True    False   False
3   file2   False   False   True
4   file2   False   True    False
5   file2   False   False   True
6   file3   True    False   False
7   file3   False   True    False
8   file3   False   False   True

文件1有prop1 true 2次,文件2有prop3 2次,文件3有每个props 1次。所以我需要制作另一个像这样的数据框:

    file    prop
0   file1   prop1
1   file2   prop3
2   file3   diff (file3 props are different)

最佳答案

我们可以使用idxmax结合sum来检测max

s=df1.set_index('file').sum(level=0)

s.idxmax(1).mask(s.eq(s.max(1),axis=0).sum(1)==3,'diff')
file
file1    prop1
file2    prop3
file3     diff
dtype: object

关于python - Pandas,根据其他列值删除重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58288101/

相关文章:

python - 用其他数据框中的值替换数据框中的值

python - 在 pandas 数据框中使用 .groupby 计算唯一值

python - 使用Python或Excel vba将单个Excel单元格内容拆分为不同的单元格

python - 如何使用 python 从 MySQL 下载 BLOB .docx 文件?

python - 从 python 日期时间中提取星期并获取序列号?

python - 如何在 Python 中找到字符的开始和结束出现

python - Python 中的正则表达式查找表中的行

python - 查找在 : Block 中定义的函数

python - 在 Pandas 中将字典转换为对称/距离矩阵的最有效方法

python - 使用 df.resample 时如何使 NaN 值总和为 NaN 而不是 0?