[英]how to extract string and create new column in python using list comprehension?
I have a data frame (df) having "Name" column我有一个具有“名称”列的数据框(df)
Name
t_gh_m
t_mr_h
t_gh_u
t_mr_h
t_z_z
and I want to create a column name "group" will ll give me ["gh", "mr"] in return if exist or else nun我想创建一个列名“组”会给我[“gh”,“mr”]作为回报,如果存在的话,否则nun
my approach我的方法
df["group"] = [i for i in df["Name"] for j in ["gh","mr"] if j not in i return np.nun else] df["group"] = [i for i in df["Name"] for j in ["gh","mr"] if j not in i return np.nun else]
But it is an error但这是一个错误
Expected output预期 output
Name group
t_gh_m "gh"
t_mr_h "mr"
t_gh_u "gh"
t_mr_h "mr"
t_z_z nan
You are looking for the pandas str (regex) extract
method:您正在寻找 pandas str (regex)
extract
方法:
df['group'] = df['Name'].str.extract('_(..)_')
Something like in this question would probably work here:类似这个问题的东西可能在这里起作用:
[ Pandas make new column from string slice of another column [ Pandas 从另一列的字符串切片创建新列
df['group'] = df.Name.str[3:5] df['group'] = df.Name.str[3:5]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.