I want to extract the type, month and year of the email campaign. Values in campaign
column is string. I applied the split method and then try to use mapping function to extract the info to different columns. I don't know why the mapping failed for the campaign_month
extraction.
emailClick_df['campaign_info'] = emailClick_df['campaign'].str.split('-')
emailClick_df['campaign_type'] = emailClick_df['campaign_info'].map(lambda x:x[0])
emailClick_df['campaign_month'] = emailClick_df['campaign_info'].map(lambda x:x[1])
emailClick_df['campaign_year'] = emailClick_df['campaign_info'].map(lambda x:x[2])
You can split with expand
parameter and then set all three columns in one go:
df[['campaign_type', 'campaign_month', 'campaign_year']] = \
df['campaign'].str.split('-', expand=True)
df
Output:
campaign campaign_type campaign_month campaign_year
0 Standard-Mar19-2020 Standard Mar19 2020
PS Your error indicates that most likely some campaign_info
values were not in the form type-month-year
and were therefore not split into a list of multiple strings, so the attempt to get second value in the list fails. Otherwise your approach should have been fine as well. You can find those problematic records with
df[df['campaign'].str.split('-').str.len() != 3]
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.