0

I have a data frame (df) having "Name" column

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

my approach
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

 Name       group
t_gh_m       "gh"
t_mr_h       "mr"
t_gh_u       "gh"
t_mr_h       "mr"
t_z_z        nan
Amit
  • 763
  • 1
  • 5
  • 14

2 Answers2

0

You are looking for the pandas str (regex) extract method:

df['group'] = df['Name'].str.extract('_(..)_')
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

Something like in this question would probably work here:

[Pandas make new column from string slice of another column

df['group'] = df.Name.str[3:5]

elgs
  • 33
  • 4