简体   繁体   中英

Copy Certain substrings from one column to another?

I have a column of text of many rows. For instance:

"Saturday morning was nice"
"Yesterday was Friday"
"He went to the store at night"

How can I extract certain keywords, say the days of the week ("Monday", "Tuesday", "Wednesday", etc.) from every row and store it in a new column. I'd rather not loop. Maybe use a lambda function?

No need lambda , here is findall

#l=['Monday',...'Sunday'] define you own list
df['Newcol']=df.Date.str.findall('|'.join(l))
0    [Saturday]
1      [Friday]
2            []
Name: Date, dtype: object

You can use pandas.Series.str.extract for this:

words = ['Saturday', 'Friday']
df['Word'] = df['Strings'].str.extract(r'({})'.format('|'.join(words)))

print(df)

                         Strings      Word
0      Saturday morning was nice  Saturday
1           Yesterday was Friday    Friday
2  He went to the store at night       NaN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM