简体   繁体   中英

How to extract elements from lists in column using pandas?

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])

Error Message table

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.

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