How to expand one column in Pandas to many columns?
Asked Answered
A

4

10

As the title, I have one column (series) in pandas, and each row of it is a list like [0,1,2,3,4,5]. Each list has 6 numbers. I want to change this column into 6 columns, for example, the [0,1,2,3,4,5] will become 6 columns, with 0 is the first column, 1 is the second, 2 is the third and so on. How can I make it?

Abbreviate answered 21/3, 2017 at 7:3 Comment(0)
N
12

Not as fast as @jezrael's solution. But elegant :-)

apply with pd.Series

df.a.apply(pd.Series)

   0  1  2  3  4  5
0  0  1  2  3  4  5
1  0  1  2  3  4  5

or

df.a.apply(pd.Series, index=list('abcdef'))

   a  b  c  d  e  f
0  0  1  2  3  4  5
1  0  1  2  3  4  5
Natale answered 21/3, 2017 at 7:15 Comment(2)
bigdata - it will be very slow ;)Lifegiving
@Lifegiving yes it willNatale
L
7

You can convert lists to numpy array by values and then use DataFrame constructor:

df = pd.DataFrame({'a':[[0,1,2,3,4,5],[0,1,2,3,4,5]]})
print (df)
                    a
0  [0, 1, 2, 3, 4, 5]
1  [0, 1, 2, 3, 4, 5]

df1 = pd.DataFrame(df['a'].values.tolist())
print (df1)
   0  1  2  3  4  5
0  0  1  2  3  4  5
1  0  1  2  3  4  5

cols = list('abcdef')
df1 = pd.DataFrame(df['a'].values.tolist(), columns=cols)
print (df1)
   a  b  c  d  e  f
0  0  1  2  3  4  5
1  0  1  2  3  4  5
Lifegiving answered 21/3, 2017 at 7:4 Comment(0)
C
0

If I understood your question correctly, you are looking for a transpose operation.

df = pd.DataFrame([1,2,3,4,5],columns='a')
# .T stands for transpose
print(df.T)
Chadburn answered 21/3, 2017 at 7:7 Comment(1)
But I have 1000 rows, and I want to transfer each of all the rows into 6 individual columns..Abbreviate
K
0
import pandas as pd

# create a sample DataFrame with a column containing comma-separated values
df = pd.DataFrame({'Name': ['John,Doe', 'Jane,Smith', 'Bob,Jones']})

# split the values in the 'Name' column and create new columns for each element
df[['First Name', 'Last Name']] = df['Name'].str.split(',', expand=True)

# drop the original 'Name' column
df = df.drop('Name', axis=1)

# print the resulting DataFrame
print(df)
Klaraklarika answered 14/2, 2023 at 11:1 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.