Home > Enterprise >  pandas conditional assignment to multiple columns using .loc
pandas conditional assignment to multiple columns using .loc

Time:11-25

Using pandas version 1.0.5

I have a following dataframe:

test = {'Price': ['Free','free', '-16.66', 'Name', '']}
df = pd.DataFrame(test)
df.loc[df['Price'].astype(str).str.contains(':'), ['col_1', 'col_2']] = df['Price'].astype(str).str.split(':',1,expand=True)

Here in this e.g. if value contains : then I need to split the values and need to assign two parts to two new cols col_1 and col_2 respectively.

But I get this error:

KeyError: "None of [Index(['col_1', 'col_2'], dtype='object')] are in the [columns]"

What am I missing here?

EDIT: I tried without .loc

df[df['Price'].astype(str).str.contains(':'), ['col_1', 'col_2']] = df['Price'].astype(str).str.split(':',1,expand=True)

And got this error:

TypeError: 'Series' objects are mutable, thus they cannot be hashed

CodePudding user response:

If not possible upgrade create columns with empty values:

df = df.assign(col_1=np.nan, col_2=np.nan)

df.loc[df['Price'].astype(str).str.contains(':'), ['col_1', 'col_2']] = df['Price'].astype(str).str.split(':',1,expand=True)

Another idea, thanks @azro working for me if there is at least one value with ::

df[['col_1', 'col_2']] = df['Price'].astype(str).str.split(':',1,expand=True)

CodePudding user response:

Check this out :)

test = {'Price': ['Free','free', '-16.66', 'Name', '', "what:yes"]}
df = pd.DataFrame(test)
df[['one', 'two']] = df['Price'].astype(str).str.split(':',1,expand = True)
df.fillna('')

Output:

    Price       one     two
0   Free        Free    
1   free        free    
2   -16.66      -16.66  
3   Name        Name    
4           
5   what:yes    what    yes
  • Related