0

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.

4 Answers 4

1

Here is a way by using apply.

df.apply(pd.Series.explode).loc[0]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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

If you want to add column names,

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

Comments

0

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'>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.