【问题标题】:select DataFrame Rows Based on multiple conditions on columns when column name are in a list当列名在列表中时,根据列上的多个条件选择 DataFrame Rows
【发布时间】:2019-08-01 13:02:43
【问题描述】:

我需要在某些列的某些条件下过滤行。 这些列存在于列表中。所有列的条件都相同,也可以不同。对于我的工作,条件是一样的。

不工作

labels = ['one', 'two', 'three']

df = df [df [x] == 1 for x in labels]  

以下代码有效:

df_list = []

for x in labels:

  df_list.append(df[(df [x] == 1)])

df5 = pd.concat(df_list).drop_duplicates()

创建不同的数据框并通过避免重复来连接它们。

预期: 它应该过滤掉那些列的值为 1 的行。

实际: ValueError:要解包的值太多(应为 1)

我了解错误的原因。有什么方法可以通过修改 not working code 来构造条件?

【问题讨论】:

标签: pandas dataframe


【解决方案1】:

我认为您可以使用以下内容重写此内容。

labels = ['one','two','three']

df5 = df[(df[labels] == 1).any(1)]

让我们用这个 MCVE 进行测试:

#Create test data
df = pd.DataFrame(np.random.randint(1,5,(10,5)), columns=[*'ABCDE'])
labels = ['A','B','E']

#Your code
df_list = []
for x in labels:

  df_list.append(df[(df [x] == 1)])

df5 = pd.concat(df_list).drop_duplicates()


#Suggested modification
df6 = df[(df[labels] == 1).any(1)]

他们是平等的吗?

df5.eq(df6)

输出:

      A     B     C     D     E
1  True  True  True  True  True
4  True  True  True  True  True
6  True  True  True  True  True
7  True  True  True  True  True
8  True  True  True  True  True

【讨论】:

    【解决方案2】:

    你需要这个吗?

    new_df = df[(df['one'] == 1) & (df['two']== 1) & (df['three'] == 1)].drop_duplicates()
    

    【讨论】:

      猜你喜欢
      • 2020-01-14
      • 1970-01-01
      • 2021-12-11
      • 2020-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      相关资源
      最近更新 更多