首页 > 解决方案 > 从字符串列列表创建布尔列

问题描述

我在每一行都有一列liststring字符串的数量不同)。我已经根据列中的字符串创建了几个类别,现在我想检查类别是否可用,我将为该类别放置一个。

list我正在使用的 cusine_type 是

['north indian','chinese','south indian','continental','cafe','fast food','beverages','italian','american','desserts','rest_cuisines']

我写了一个代码,基本上是 2 个 forloops,只有少数 if 循环支持逻辑,但这段代码很慢。我需要一些耗时较少的解决方案。

for i in temp.index:
    split = temp['cuisines'].iloc[i].split(',')
    for string in split:
        string=string.strip()
        if string in cusine_type:

            if temp.loc[i,string]==0:

                temp.loc[i,string]=1          
        else:
            temp.loc[i,'rest_cusines']=1

我希望输出如下表:

在此处输入图像描述

标签: pythonpandas

解决方案


相信你需要str.get_dummies。对于您的样品:

new_df = df1.cuisines.str.get_dummies(sep=', ')

给出:

   cafe  chinese  italian  mexican  north indian  south indian  thai
0     0        1        0        0             1             0     0
1     0        1        0        0             1             0     1
2     1        0        1        1             0             0     0
3     0        0        0        0             1             1     0
4     0        0        0        0             1             0     0

转换合并所有rest_cuisines

# get their names
not_in_list = [col for col in new_df.columns if col not in cuisine_list]

# merge into rest_cuisines:
new_df['rest_cusines'] = new_df[not_in_list].max(1)

如果你想要整个列表,你可以这样做:

new_df.reindex(cuisine_list, axis=1, fill_value=0)

然后附加到原始数据框:

df = pd.concat((df, new_df), axis=1)

推荐阅读