Home > Software engineering >  How to add new column's name in dataframe saving previous one (python)?
How to add new column's name in dataframe saving previous one (python)?

Time:06-29

have this with column name = A:

   A
0  B
1  C
2  D

How to make this with column name = N:

   N
0  A
1  B
2  C
3  D

this not working in my case:

df.columns = ['N']

is it pandasmic way?)

CodePudding user response:

Try this:

df.T.reset_index().set_axis(['N']).T.reset_index(drop=True)

Output:

   N
0  A
1  B
2  C
3  D

It is a lot easier to move a dataframe index into the columns of a dataframe than to move the column header of a dataframe into a row of a dataframe.


pd.concat([df.columns.to_series(name='A').to_frame(),df])\
  .reset_index(drop=True).rename(columns={'A':'N'})

Output:

   N
0  A
1  B
2  C
3  D

CodePudding user response:

You can build a new dataframe by adding the column names at the start of the df.

out = pd.DataFrame({'N': [*df.columns, *df.squeeze()]})

   N
0  A
1  B
2  C
3  D

We can also use pd.concat here.

out = pd.concat(
    [df.columns.to_series(), df.squeeze()], ignore_index=True
).to_frame("N")

   N
0  A
1  B
2  C
3  D
  • Related