Nemo
Nemo

Reputation: 1227

AttributeError: can't delete attribute

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.

Upvotes: 4

Views: 8566

Answers (4)

Gaurav Joshi
Gaurav Joshi

Reputation: 1

df2.columns.name = None

df2.index.name = None

Try this code.

Upvotes: -1

Teymur Mammadov
Teymur Mammadov

Reputation: 1

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

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

Upvotes: 0

jezrael
jezrael

Reputation: 862406

Use DataFrame.rename_axis:

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

Upvotes: 2

Swetank Poddar
Swetank Poddar

Reputation: 1291

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)

Upvotes: 0

Related Questions