teteh May
teteh May

Reputation: 455

Converting Lists within Pandas Dataframe into New DataFrame

I have a dataframe:

df =

   col1                col2
0  [0.1,0.2,0.3]       [1,2,3]
1  [0.5,0.6,0.7]       [11,12,13]

My goal: to re-create data frame from index 0:

new_df = 
   new_col1    new_col2
0   0.1          1
1   0.2          2
2   0.3          3

What I tried was trying to access row by row:

new_col1 = df.col1[0]
new_col2 = df.col2[0]

But new_col1 results in below instead of a list. So I am unsure how to approach this.

0    [0.1,0.2,0.3]
Name: col1, dtype: object

Thanks.

Upvotes: 0

Views: 55

Answers (4)

Syed
Syed

Reputation: 146

you can use the list() function for this

>>> new_col1
[0.1, 0.2, 0.3]
>>> new_col1_=list(new_col1)
[0.1, 0.2, 0.3]
>>> type(new_col1_)
<class 'list'>

Upvotes: 0

Cat Mai
Cat Mai

Reputation: 470

new_df = pd.DataFrame([new_col1, new_col2]).transpose()

If you want to add column names,

new_df.columns = ["new_col1","new_col2"]

Upvotes: 0

rhug123
rhug123

Reputation: 8768

Here is a way by using apply.

df.apply(pd.Series.explode).loc[0]

Upvotes: 1

jezrael
jezrael

Reputation: 862431

You can create new DataFrame by select first row by DataFrame.loc or DataFrame.iloc and then transpose by DataFrame.T with DataFrame.add_prefix for new columns names:

df1 = pd.DataFrame(df.iloc[0].tolist(), index=df.columns).T.add_prefix('new_')
print (df1)
   new_col1  new_col2
0       0.1       1.0
1       0.2       2.0
2       0.3       3.0

Upvotes: 0

Related Questions