首页 > 解决方案 > 确保值列表中的每个值在 pandas 数据框的每一行中仅出现一次

问题描述

如何确保一组特定值中的每个值在熊猫数据框的每一行中只出现一次?

例如:

VALUES = [1, 2]
df_no = pd.DataFrame(
    {
        "a": [1, 2],
        "b": [1, 2],
    }
)
df_yes = pd.DataFrame(
    {
        "a": [1, 2],
        "b": [2, 4],
        "c": [3, 1],
    }
)

以下作品:


def check(data, values):
    for row in data.itertuples(index=False):
        row_values = [x for x in row if x in values]
        if len(row_values) != len(set(row_values)):
            return False
        return True


check(data=df_no, values=VALUES) # False
check(data=df_yes, values=VALUES) # True

我觉得有一种更清洁的方法,itertuples感觉就像一个警告信号。

标签: pythonpandas

解决方案


想法比较dicts来自Counter

from collections import Counter

s = set(Counter(VALUES).items())
x = all(s.issubset(Counter(x).items()) for x in df_no.to_numpy())

df = pd.DataFrame(
    {
        "a": [1, 2],
        "b": [2, 1],
        "c": [1, 2],
        "d": [2, 1],
    }
)

from collections import Counter

s = set(Counter(VALUES).items())
x = all(s.issubset(Counter(x).items()) for x in df.to_numpy())
print (x)
False

推荐阅读