python - 使用条件,在 pandas DataFrame 中选择所需的列

标签 python pandas conditional-statements

我有一个使用 pandas 创建的 DataFrame,我想基于原始表创建新表,但要根据特定条件进行过滤。

df = pd.DataFrame(
    [['Y', 'Cat', 'no', 'yes', 6],
    ['Y', 4, 7, 9, 'dog'],
    ['N', 6, 4, 6, 'pig'],
    ['N', 3, 6, 'beer', 8]],
    columns = ('Data', 'a', 'b', 'c', 'd')
)

我的条件不起作用:

if (df['Data']=='Y') & (df['Data']=='N'):
    df3=df.loc[:,['Data', 'a', 'b', 'c']]
else:
    df3=df.loc[:,['Data', 'a', 'b']]

我希望新表包含符合以下条件的数据:

如果 df.Data 有值 'Y' 和 'N',新表获取列 ('Data', 'a', 'b')

如果不是,则新表获取列 ('Data', 'a', 'b', 'c')

 Data    a   b
0    Y  Cat  no
1    Y    4   7
2    N    6   4
3    N    3   6

  Data    a   b     c
0    Y  Cat  no   yes
1    Y    4   7     9
2    Y    6   4     6
3    Y    3   6  beer

最佳答案

您正在将一个系列与一个字符进行比较,而不是检查单个 bool 结果是否存在。相反,您可以使用 pd.Series.any 如果系列中的任何值为 True 则返回 True:

if (df['Data']=='Y').any() & (df['Data']=='N').any():
    # do something

另一种方法是使用带有三元语句的 pd.DataFrame.drop:

df = df.drop(['d'] if set(df['Data']) == {'Y', 'N'} else ['c', 'd'], 1)

print(df)

  Data    a   b     c
0    Y  Cat  no   yes
1    Y    4   7     9
2    N    6   4     6
3    N    3   6  beer

关于python - 使用条件,在 pandas DataFrame 中选择所需的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50724040/

相关文章:

python - Google App Engine 在 Python/Flask API 上产生 502 错误

python - BeautifulSoup "AttributeError: ' NoneType'对象没有属性 'text'“

python - 为 panda 数据帧创建 x 和 y 坐标和时间戳的多重索引

python - 如何从 Pandas 系列中获取最大值和名称?

c# - 如果条件在 linq

conditional-statements - NLog 条件变量值

Python 将嵌套元组列表转换为字典

python - 我可以将列表中的 2 个连续空字符串合并为 1 个空字符串,这样当我们有 4 个空字符串时,它应该合并并生成 2 个空字符串

python - Pandas 奇怪的 SettingWithCopyWarning 警告

SQL 存储查询 - 根据记录的存在使用查询结果作为 bool 值