根据字母 'l' 或 'L' 是否在另一列的字符串中创建新列

creating new column based on whether the letter 'l' or 'L' is in the string of another column

我正在使用非常混乱的 Open Food Facts 数据集。 有一个名为数量的列,其中包含有关各种食物数量的信息。 条目看起来像:

365 g (314 ml)  
992 g  
2.46 kg  
0,33 litre  
15.87oz  
250 ml   
1 L    
33 cl  

...等等(很乱!!!) 我想创建一个名为 is_liquid 的新列。 我的想法是,如果数量字符串包含 lL,则此行中的 is_liquid 字段应为 1,如果不是 0,则应为 0。 这是我试过的: 我写了这个函数:

def is_liquid(x):
    if x.str.contains('l'):  
        return 1  
    elif x.str.contains('L'):  
        return 1  
    else: return 0  

(顺便说一句:如果用 'oz' 测量某物是液体吗?)

然后尝试应用它

df['is_liquid'] = df['quantity'].apply(is_liquid)

但我得到的只是这个错误:

AttributeError: 'str' object has no attribute 'str'

有人可以帮我吗?

使用str.contains with case=False for boolean mask and convert it to integers by Series.astype:

df['is_liquid']= df['liquids'].str.contains('L', case=False).astype(int)
print(df)
          liquids  is_liquid
0  365 g (314 ml)          1
1           992 g          0
2         2.46 kg          0
3      0,33 litre          1
4         15.87oz          0
5         250 ml           1
6             1 L          1
7           33 cl          1