Home > Enterprise >  Converting columns into rows and adding separate header later in pandas
Converting columns into rows and adding separate header later in pandas

Time:09-30

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

CodePudding user response:

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

CodePudding user response:

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"])
  • Related