2

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
6
  • 2
    What is your pandas version? For me working well Commented Nov 25, 2021 at 7:34
  • @jezrael 1.0.5 Commented Nov 25, 2021 at 7:35
  • It is old version, try upgrade. Commented Nov 25, 2021 at 7:36
  • it is version from 2020-06-17, latest is 1.3.4 Commented Nov 25, 2021 at 7:36
  • Don't use loc. Try to just use df['Price'].astype(str).str.split(':',1,expand = True) Commented Nov 25, 2021 at 7:41

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

does something like df[['col_1', 'col_2']] = df['Price'].astype(str).str.split(':',1,expand=True) may work ? I don't know if there is that kind of syntax, like unpacking
@azro - hmm, it should working, because append DF, not sure about ol pandad version. But add to answer.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.