I have an existing solution to split a dataframe with one column into 2 columns.
df['A'], df['B'] = df['AB'].str.split(' ', 1).str
Recently, I got the following warning FutureWarning: Columnar iteration over characters will be deprecated in future releases.
How to fix this warning?
I’m using python 3.7
Advertisement
Answer
That’s not entirely correct, plus the trailing .str does not make sense. Since split with expand returns a DataFrame, this is easier:
df[['A', 'B']] = df['AB'].str.split(' ', n=1, expand=True)
Your existing method without expand returns a single Series with a list of columns. I’m not sure what version of pandas used to work with your code but AFAIK you’ll need to make some tweaks for this to work with pandas (>= 1.0) today. Assignment in this way is tedious but still possible.
s = df['AB'].str.split(' ', n=1)
df['A'], df['B'] = s.str[0], s.str[1]
I prefer the expand solution as it’s a line shorter.
