Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expand one column in Pandas to many columns?

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?

like image 801
Liu Chong Avatar asked Mar 21 '17 07:03

Liu Chong


People also ask

How do I convert one column to multiple columns in pandas?

split() function is used to break up single column values into multiple columns based on a specified separator or delimiter. The Series. str. split() function is similar to the Python string split() method, but split() method works on the all Dataframe columns, whereas the Series.

How do I expand a column in pandas DataFrame?

Pandas DataFrame - expanding() functionThe expanding() function is used to provide expanding transformations. Minimum number of observations in window required to have a value (otherwise result is NA). Set the labels at the center of the window.

How do I split a text column into two separate columns?

Select the cell or column that contains the text you want to split. Select Data > Text to Columns. In the Convert Text to Columns Wizard, select Delimited > Next. Select the Delimiters for your data.

How do I add multiple columns in pandas?

Add multiple columns to a data frame using Dataframe. assign() method. Using DataFrame. assign() method, we can set column names as parameters and pass values as list to replace/create the columns.


2 Answers

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
like image 183
piRSquared Avatar answered Oct 06 '22 20:10

piRSquared


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
like image 32
jezrael Avatar answered Oct 06 '22 21:10

jezrael