python - 从字符串列列表创建布尔列
问题描述
我在每一行都有一列list
(string
字符串的数量不同)。我已经根据列中的字符串创建了几个类别,现在我想检查类别是否可用,我将为该类别放置一个。
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
我希望输出如下表:
解决方案
相信你需要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)
推荐阅读
- javascript - 使用 moment.js 动态更改倒计时值
- sapui5 - 如何将多个复选框与其标签放在一行中?
- node.js - Stripe Checkout - 结帐页面上是否可以显示多个图像?
- css - 响应式背景图像及其内容
- python - 为我的 QLearning 代理编写一个好的奖励函数
- python - 从现有数据重新创建反向数据帧
- python-3.x - 将复数转换为极坐标
- ckeditor - 如何使用 gatsby 静态站点生成器生成 ckeditor 输出的真实 html?
- excel - 对象_worksheet的Excel VBA方法范围失败错误
- javascript - 如何根据cropper js中的图像设置初始缩放幻灯片值