How to leave certain values (which have a comma in them) intact when separating list-values in strings in pandas?

Viewed 25

From the dataframe, I create a new dataframe, in which the values from the "Select activity" column contain lists, which I will split and transform into new rows. But there is a value: "Nothing, just walking", which I need to leave unchanged. Tell me, please, how can I do this?

The original dataframe looks like this:

    Name    Age   Select activity                 Profession
0   Ann     25    Cycling, Running                Saleswoman
1   Mark    30    Nothing, just walking           Manager
2   John    41    Cycling, Running, Swimming      Accountant

My code looks like this:

df_new = df.loc[:, ['Name', 'Age']]
df_new['Activity'] = df['Select activity'].str.split(', ')
df_new = df_new.explode('Activity').reset_index(drop=True)

I get this result:

    Name    Age   Activity
0   Ann     25    Cycling
1   Ann     25    Running
2   Mark    30    Nothing
3   Mark    30    just walking
4   John    41    Cycling
5   John    41    Running
6   John    41    Swimming

In order for the value "Nothing, just walking" not to be divided by 2 values, I added the following line:

if df['Select activity'].isin(['Nothing, just walking']) is False:

But it throws an error.

1 Answers

then let's look ahead after comma to guarantee a Capital letter, and only then split. So instead of , we have , (?=[A-Z])

df_new = df.loc[:, ["Name", "Age"]]
df_new["Activity"] = df["Select activity"].str.split(", (?=[A-Z])")
df_new = df_new.explode("Activity", ignore_index=True)

i only changed the splitter, and ignore_index=True to explode instead of resetting afterwards (also the single quotes..)

to get

>>> df_new

   Name  Age               Activity
0   Ann   25                Cycling
1   Ann   25                Running
2  Mark   30  Nothing, just walking
3  John   41                Cycling
4  John   41                Running
5  John   41               Swimming

one line as usual
df_new = (df.loc[:, ["Name", "Age"]]
            .assign(Activity=df["Select activity"].str.split(", (?=[A-Z])"))
            .explode("Activity", ignore_index=True))
Related