Home > Mobile >  Extracting comma separeted values to make new columns
Extracting comma separeted values to make new columns

Time:11-23

I have a df with only one column. The dtype is object:

column_1
1,2,3
2,3,4

I want to extracted those comman separeted values to make new columns,like this:

 column_1     column_2    column_3    column_4
    1,2,0.3        1           2          0.3
    2,3,0.4        2           3          0.4

I tried something with .split(',') but it's failed.

What's the best way to do it?

Thanks

CodePudding user response:

Try with split

out = df.join(pd.DataFrame(df.column_1.str.split(',').tolist(),index=df.index))
Out[275]: 
  column_1  0  1  2
0    1,2,3  1  2  3
1    2,3,4  2  3  4

CodePudding user response:

use split with the expand=True option

txt="""
column_1
1,2,3
2,3,4
"""
df=pd.read_csv(io.StringIO(txt),sep='\n')
df[['column_2','column_3','column_4']]=df['column_1'].str.split(',',expand=True)
print(df)

output:

column_1 column_2 column_3 column_4
0    1,2,3        1        2        3
1    2,3,4        2        3        4

CodePudding user response:

Here's how I would do it:

df[["Column_%d"%i for i in range(2,5)]] = df['column_1'].str.split(',', expand=True)
  • Related