gpt4 book ai didi

python - 在 pandas DataFrame 中使用多个条件会导致 ValueError

转载 作者:行者123 更新时间:2023-12-01 01:22:30 24 4
gpt4 key购买 nike

我有一个这样的数据表:

       Item Colour    Item Range Item Size
789 COLOUR-BLUE RANGE-PANT SIZE-XXL
2507 COLOUR-BLACK RANGE-OTHER SIZE-XXL
2376 COLOUR-BLACK RANGE-JACKET SIZE-S
1378 COLOUR-WHITE RANGE-OTHER SIZE-L
598 COLOUR-BLUE RANGE-JACKET SIZE-M
1589 COLOUR-BLUE RANGE-JACKET SIZE-L
2580 COLOUR-BLACK RANGE-SHIRT SIZE-L
366 COLOUR-BLUE RANGE-PANT SIZE-XXL
2320 COLOUR-WHITE RANGE-OTHER SIZE-L
1247 COLOUR-GREEN RANGE-PANT SIZE-M
2224 COLOUR-BLACK RANGE-JACKET SIZE-L
3615 COLOUR-BLACK RANGE-OTHER SIZE-S
4176 COLOUR-GREEN RANGE-PANT SIZE-XL
1640 COLOUR-BLACK RANGE-PANT SIZE-S
1136 COLOUR-WHITE RANGE-OTHER SIZE-M
3437 COLOUR-BLACK RANGE-JACKET SIZE-S
4448 COLOUR-WHITE RANGE-OTHER SIZE-S
1188 COLOUR-WHITE RANGE-SHIRT SIZE-XXL
3332 COLOUR-GREEN RANGE-OTHER SIZE-M
1080 COLOUR-WHITE RANGE-OTHER SIZE-XXL

我只想使用以下掩码获取数据的子选择:

mask = (df['Item Colour'] == 'COLOUR-WHITE') & (df['Item Range'] in ['RANGE-JACKET','RANGE-PANT']) & (df['Item Size'] not in ['SIZE-XXL'])

我尝试了df[mask],但它给了我错误:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

如何避免错误。

到目前为止我已经这样做了:

import numpy as np
import pandas as pd

df = pd.read_clipboard()
df.drop(['Item','Item.2','Size'], inplace=True,axis=1)
df.columns = ['Item Colour', 'Item Range', 'Item Size']
print(df)

mask = (df['Item Colour'] == 'COLOUR-WHITE') & (df['Item Range'] in ['RANGE-JACKET','RANGE-PANT']) & (df['Item Size'] not in ['SIZE-XXL'])

dff = df[mask]
dff

更新还是不行。

mask =  (df['Item Colour'] == 'COLOUR-WHITE').all()\
& (df['Item Range'] in ['RANGE-JACKET','RANGE-PANT']).all()\
& ( ~df['Item Size'].isin(['SIZE-XXL']).all())

df[mask]

最佳答案

问题出在您通过检查项目是否在列表中来构建掩码的方式上。您可以使用 pd.Series.isin([item1, item2, ...]) Series 方法来执行此操作。所以,而不是:

df['Item Range'] in ['RANGE-JACKET','RANGE-PANT'],

做:

df['元素范围'].isin(['RANGE-JACKET','RANGE-PANT'])

否定,对于“不在”:

df['商品尺寸'] 不在 ['SIZE-XXL'] 范围内

你可以这样做:

~df['商品尺寸'].isin(['SIZE-XXL'])

关于python - 在 pandas DataFrame 中使用多个条件会导致 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53687088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com