Home > OS >  splitting columns with str.split() not changing the outcome
splitting columns with str.split() not changing the outcome

Time:04-16

Will I have to use the str.split() for an exercise. I have a column called title and it looks like this:

enter image description here

and i need to split it into two columns Name and Season, the following code does not through an error but it doesn't seem to be doing anything as well when i'm testing it with df.head()

   df[['Name', 'Season']] = df['title'].str.split(':',n=1, expand=True)

Any help as to why?

CodePudding user response:

The code you have in your question is correct, and should be working. The issue could be coming from the execution order of your code though, if you're using Jupyter Notebook or some method that allows for unclear ordering of code execution.

I recommend starting a fresh kernel/terminal to clear all variables from the namespace, then executing those lines in order, e.g.:

# perform steps to load data in and clean
print(df.columns)
df[['Name', 'Season']] = df['title'].str.split(':',n=1, expand=True)
print(df.columns)

Alternatively you could add an assertion step in your code to ensure it's working as well:

df[['Name', 'Season']] = df['title'].str.split(':',n=1, expand=True)
assert {'Name', 'Season'}.issubset(set(df.columns)), "Columns were not added"
  • Related