Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract row from a data frame and make it a new data frame and change its index as like column value

I have a data frame df like this

import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([[0,2,5,3], [3,1,4,2], [1,3,5,2], [5,1,3,4], [4,2,5,1], [2,3,5,1]]))
df

Now, I need first row of data frame and make it another data frame

df=df.iloc[0]

df

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

like

0    0
2    2
5    5
3    3 

but my output come like

0    0
1    2
2    5
3    3 

>Solution :

Use rename for convert indices:

s = df.iloc[0].rename(df.iloc[0])
print (s)
0    0
2    2
5    5
3    3
Name: 0, dtype: int32

If need one column DataFrame:

df1=df.iloc[0].rename(df.iloc[0]).to_frame('col')
print (df1)
   col
0    0
2    2
5    5
3    3

Or:

s = pd.Series(df.iloc[0].to_numpy(), index=df.iloc[0])
#for oldier pandas versions
#s = pd.Series(df.iloc[0].values, index=df.iloc[0])
print (s)
0    0
2    2
5    5
3    3
dtype: int32
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading