0

Hi i'm trying to pivot a df. I would like to convert column values to row headers. Thanks in advance.

How can I change this:

name
0   countryCode
1   vatNumber
2   requestDate
3   valid
4   name
5   address

to this in python?

name  countryCode  vatNumber requestDate valid name address
0
3
  • can't you use a transpose? df.T? what is print(df.columns) Commented Mar 17, 2019 at 9:57
  • Hi anky, yes you are right. did a df.transpose() and it worked, however they are still not headers. 0 1 2 3 4 5 name countryCode vatNumber requestDate valid name address` Commented Mar 17, 2019 at 9:59
  • what is print(df.columns) Commented Mar 17, 2019 at 10:03

1 Answer 1

2

You can use, df.T as below:

df = pd.DataFrame({'name': ['countryCode', 'vatNumber','requestDate', 'valid', 'name', 'address']})

df = df.T
df

             0        1          2            3          4        5
name    countryCode vatNumber   requestDate valid      name    address

df.columns = df.values[0]
df = df.reset_index(drop = True)
df


    countryCode vatNumber   requestDate valid   name    address
0   countryCode vatNumber   requestDate valid   name    address

Then replace all non null values with np.nan:

df[df.notna()] = np.nan
df
countryCode vatNumber   requestDate valid   name    address
0   NaN        NaN          NaN       NaN   NaN      NaN
Sign up to request clarification or add additional context in comments.

3 Comments

Hi Mohit, thanks for the prompt reply. Can I also remove index 0 or should this be filled?
HI @mrichman I don't think you can remove the index. Do you want a different index?
I'm planning to do a loop on an API and would like to append the right values to the right column names. Is this the way to go? Thanks in advance.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.