简体   繁体   English

如何使用列表理解在 python 中提取字符串并创建新列?

[英]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.

相关问题 使用列表理解 Python 创建新列 - Create New Column With List Comprehension Python 熊猫使用列表理解来创建新列 - pandas using list comprehension to create new column 如何从字符串列表中提取数字以在 python 的新列中? - How to extract number from a list of string to be in a new column with python? 使用列表推导和数据框中的字符串序列派生新列 - Deriving new column using list comprehension and a string series in the dataframe 如何使用 2 个列表中的 python 列表理解创建字典 - How to create a dictionary using python list comprehension from 2 list 如何使用 Python 中的列表理解将字符串转换为 char 和 int 列表 - How to transform a string into a list of char and int using a list comprehension in Python Python:使用列表推导创建字典列表 - Python: create a list of dictionaries using a list comprehension 在Python中提取一个包含字符串的列表项,而无需列表理解? - Extract a list item in Python that contains a string, without list comprehension? Python如何在pandas数据帧的[]括号内提取指定的字符串,并创建一个具有布尔值的新列 - Python How to extract specified string within [ ] brackets in pandas dataframe and create a new column with boolean values 使用列表理解的Python部分字符串匹配 - Python partial string match using list comprehension
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM