![](/img/trans.png)
[英]Is there a way to create a new column based on a substring and text that follow it?
[英]Create new column based on substring
我正在尝试根据原始列中的字符串是否包含某个 substring 创建一个新列。 我尝试的是这样的:
def get_group(row):
stores = pd.Series(row['store'])
if (stores.str.contains('Blue')): 'Blue'
elif (stores.str.contains('Yellow')): 'Yellow'
elif (stores.str.contains('Green')): 'Green'
elif (stores.str.contains('Red')): 'Red'
elif (stores.str.contains('Purple')): 'Purple'
elif (stores.str.contains('Pink')): 'Pink'
elif (stores.str.contains('Orange')): 'Orange'
else: 'Outhers'
db['group'] = db.apply(lambda row: get_group(row), axis=1)
但是它不起作用
您的 function 中缺少退货。 此外,要检查字符串是否包含 substring,您必须使用in
。 最后,您的pd.Series(row['store'])
是错误的。
您的 function 应如下所示:
def get_group(row):
stores = row['store']
to_return='Others'
if ('Blue' in stores): to_return='Blue'
elif ('Yellow' in stores): to_return='Yellow'
elif ('Green' in stores): to_return='Green'
elif ('Red' in stores): to_return='Red'
elif ('Purple' in stores): to_return='Purple'
elif ('Pink' in stores): to_return='Pink'
elif ('Orange' in stores): to_return='Orange'
return(to_return)
请注意,此 function 对大小写敏感,因此它不会检测到带有小写字母的“蓝色”,而只会检测到“蓝色”。
如果要使 function 不区分大小写,则必须将所有字符串转换为小写,例如: if ('blue' in stores.lower())
您需要解决两件事:
话虽如此,以下应该有效:
def get_group(row):
stores = pd.Series(row['store'])
if stores.str.contains('Blue').any(): return 'Blue'
elif stores.str.contains('Yellow').any(): return 'Yellow'
elif stores.str.contains('Green').any(): return 'Green'
elif stores.str.contains('Red').any(): return 'Red'
elif stores.str.contains('Purple').any(): return 'Purple'
elif stores.str.contains('Pink').any(): return 'Pink'
elif stores.str.contains('Orange').any(): return 'Orange'
else: return 'Others'
db['group'] = db.apply(lambda row: get_group(row), axis=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.