python - 确保值列表中的每个值在 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
感觉就像一个警告信号。
解决方案
想法比较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
推荐阅读
- eclipse - Eclipse 插件提供导游服务?
- python - 如何在 Windows 上运行 Python?
- amazon-s3 - 使用 AWS Javascript 开发工具包更新 AWS S3 视频/对象元数据
- python - 迭代嵌套字典的更优雅和有效的方法?
- java - MyBatis Resolving 参数与多个语句
- php - 如果某些内容不存在,如何使用 SQL 插入,如果存在则将其删除?
- reactjs - 如何将子索引传递给父级
- angular - 根据导航更改标题背景
- xml - CF18 中的 XmlSearch() 函数未返回预期结果?
- maven - 如何从多模块 Maven 项目构建单个 BOM