【问题标题】:Pandas - how to flag if a dataframe column has a non-permitted value in it?Pandas - 如果数据框列中包含不允许的值,如何标记?
【发布时间】:2022-07-11 23:23:03
【问题描述】:

我有一个看起来有点像这样的数据框:

offer | type
------|-----
123   | A
456   | B
789   | C

我想设置一个 if 语句,如果 type 列中包含除 A 或 B 之外的任何值,它会打印一条警告消息。值可以是大写或小写,但只能是 A 或 B。

我尝试使用下面的代码,但它不起作用 - 它返回消息说一切正常,无论类型列中是否有其他类型:

if ~df["type"].isin(["A","B","a","b"]).any():
    print("WARNING - Not all offers are the correct types!")
else:
    print("OK - All offers are the correct types.") 

请问有人知道我哪里出错了吗?

【问题讨论】:

  • 逻辑上你应该使用all()而不是any()

标签: python pandas


【解决方案1】:

试试

import pandas as pd
# sample data
df = pd.DataFrame(list('ABC'), columns=['type'])
# logic using .all()
if df['type'].isin(list('ABab')).all():
    print("OK - All offers are the correct types.") 
else:
    print("WARNING - Not all offers are the correct types!")

【讨论】:

    猜你喜欢
    • 2010-10-18
    • 2018-01-21
    • 2018-11-02
    • 2022-01-10
    • 1970-01-01
    • 2018-06-17
    • 2018-08-18
    • 1970-01-01
    • 2020-03-03
    相关资源
    最近更新 更多