14

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

cs95
  • 379,657
  • 97
  • 704
  • 746
user3848207
  • 3,737
  • 17
  • 59
  • 104
  • Related: https://stackoverflow.com/questions/14745022/how-to-split-a-column-into-two-columns – Jeff Oct 15 '20 at 19:10

2 Answers2

23

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • will the first answer work if my dataframe has more than two columns i.e. will I loose the rest of the columns by using df[['a','b']] = – Topde Aug 04 '20 at 17:56
  • Prior to pandas 0.16 the trailing str approach was, AFAIK, the main way to do this, so there is probably a lot of code out there getting this warning now. – Corvus Nov 06 '20 at 07:47
3

Or we do

df['A'], df['B']=zip(*df['AB'].str.split(' ').tolist())
df
    AB  A  B
0  A B  A  B
1  A B  A  B
2  A B  A  B
3  A B  A  B
BENY
  • 317,841
  • 20
  • 164
  • 234