4

I had this data frame df1

              Type  Count
0  Entire home/apt   5326
1       Hotel room    249
2     Private room   5570
3      Shared room    628

After transposing df1, the transposed data frame df2 looked like this

df2 = df1.T
df2 .columns = df2 .iloc[0]
df2 = df2 [1:]

print(df2.index)
Out: Index(['Count'], dtype='object')

print(df2.columns)
Out: Index(['Entire home/apt', 'Hotel room', 'Private room', 'Shared room'], dtype='object', name='Type')

print(df2)
Out:
Type    Entire home/apt Hotel room  Private room    Shared room
Count   5326            249         5570            628

I wanted to obtain a desired data frame that should look like this (where the heading Type disappeared)

        Entire home/apt Hotel room  Private room    Shared room
Count   5326            249         5570            628

by using this code to remove Type from the columns name

del df2.columns.name

However, it resulted in an error AttributeError: can't delete attribute

Could someone please explain what that meant and how to resolve it to obtain the desired data frame?

Thank you.

Edit: please note, this post didn't address my question as it removed the names/headings of the columns. I only wanted to remove the attribute name (in this case Type) of the columns name.

0

4 Answers 4

2

Use DataFrame.rename_axis:

df2 = df2.rename_axis(None, axis=1)
0
0

A version of this answer.

Pandas by default needs column names.

So you could do something like this to hide it

df2.rename(columns={'Type': ''}, inplace=True)
2
  • Thanks for your help. But renaming Type to blank still leaves something there, preventing me to graph it with streamlit.bar_chart(df2)
    – Nemo
    Commented Apr 19, 2020 at 9:20
  • 1
    Oh if you are planning to plot it further you could just say 'Type' : None? Commented Apr 19, 2020 at 12:23
0

if this doesn't work: del df2.index.name

You can run this: df2.index.name = None

1
  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Jul 12, 2023 at 9:32
-1
df2.columns.name = None

df2.index.name = None

Try this code.

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Feb 17 at 0:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.