从字符串列列表创建布尔列

2024-04-20 06:26:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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

list我使用的cusine类型是

['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

我希望输出如下表所示:

enter image description here


Tags: 字符串代码inrestforstringif类别
1条回答
网友
1楼 · 发布于 2024-04-20 06:26:51

我相信你需要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)

相关问题 更多 >