0

I am trying to convert the first column row of dataframe to add into a first row and will shift all the other rows to the bottom without losing a last row.

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,3,size=(3, 4)), columns=list('1234'))
df

dataframe output

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

expected output

    A   B   C   D
0   1   2   3   4
1   1   1   0   1
2   2   1   1   1
3   0   0   1   2

what I tried so far

df.columns.values[0:4] =["A", "B", "C", "D"]

current output

    A   B   C   D
0   1   1   0   1
1   2   1   1   1
2   0   0   1   2

I just lost the last row but I want to add column row into the first row and then add column headers

2 Answers 2

4

here is one way to do it

# add a blank row
df.loc[len(df)] = 0

#shift down the rows
df=df.shift()

#copy column values as rows
df.loc[0]=df.columns.values

#add new column names
df.columns.values[0:4] =["A", "B", "C", "D"]

#makes values int
df.astype(int)
    A   B   C   D
0   1   2   3   4
1   0   2   2   1
2   1   2   2   0
3   2   1   1   0

starting DF

    1   2   3   4
0   0   2   2   1
1   1   2   2   0
2   2   1   1   0
Sign up to request clarification or add additional context in comments.

Comments

2

Here is another solution:

df = pd.DataFrame(np.concatenate([[[1,2,3,4]], np.random.randint(0,3,size=(3, 4))], axis=0), columns=["A", "B", "C", "D"])

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.