【问题标题】:How to subset a DataFrame, using loc(), based on multiple columns having a particular value with Python?如何使用 loc() 基于 Python 中具有特定值的多个列对 DataFrame 进行子集化?
【发布时间】:2017-05-10 15:41:01
【问题描述】:

如果我想创建一个DataFrame的子集,基于一个指定列可以有多个指定值的条件,我可以这样做:

df = df.loc[df[column_name].isin(list_of_acceptable_values)]

如果我有一个列名列表,那么根据条件创建 DataFrame 子集的最佳方法是什么,该条件检查这些列是否包含特定值。例如,列名列表为:

['column_1', 'column_2', 'column_3']

我想创建一个新的 DataFrame,它只有初始数据框中的行,其中 column_1、column_2 或 column_3 中包含 0

【问题讨论】:

  • df[(df[list_of_cols] == 0).any(axis=1)] 应该可以工作

标签: python pandas


【解决方案1】:

您可以将感兴趣的列名列表传递给子集,然后与0 进行比较并使用any(axis=1) 测试一行的任何col 值:

In [9]:
df = pd.DataFrame({'a':[1,1,1,0],'b':[1,1,1,1],'c':[1,0,1,1]})
df

Out[9]:
   a  b  c
0  1  1  1
1  1  1  0
2  1  1  1
3  0  1  1

In [10]:
df[(df[['a','c']]==0).any(axis=1)]

Out[10]:
   a  b  c
1  1  1  0
3  0  1  1

如果您有预定义的列表,则无需再次使用方括号括起来:

In [12]:
col_list = ['a','c']
df[(df[col_list]==0).any(axis=1)]

Out[12]:
   a  b  c
1  1  1  0
3  0  1  1

【讨论】:

  • 很好的答案,谢谢。我遇到的一个问题是,当事先不知道列表值时,我不能这样做。例如。 columns_list = ['cooking', 'pets'] df[(df[[columns_list]]==0).any(axis=1)] 给了我一个 TypeError: unhashable list。我需要传递一个预先填充的列表。抱歉,问题没有更清楚。
  • 查看更新的答案,基本上如果你已经有一个列表,那么你不需要额外的方括号
猜你喜欢
  • 2017-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-25
  • 1970-01-01
  • 2023-02-26
  • 1970-01-01
  • 2020-01-22
相关资源
最近更新 更多