简体   繁体   中英

Column name is not referencing in pandas dataframe

I took transporse of a dataframe and give name 'District' to extra column get after transporse.

df.index = pd.Index(['Active','Confirmed','Deceased','Recovered'],name='District') finaldf=df.T

My finaldf dataframe contains District column After that when I am taking this finaldf.District

getting below error

AttributeError: 'DataFrame' object has no attribute 'District'

Please help me on this

Sample :

df = pd.DataFrame(np.random.rand(4,3), columns=list('abc'))

Here is problem District is not column, by axis name, so you can select it by df.index :

finaldf1=df.T
print (finaldf1)
District    Active  Confirmed  Deceased  Recovered
a         0.716292   0.672918  0.559143   0.206168
b         0.448028   0.196304  0.831332   0.511764
c         0.048026   0.943950  0.339930   0.990788

print (finaldf1.columns)
Index(['Active', 'Confirmed', 'Deceased', 'Recovered'], dtype='object', name='District')

print (finaldf1.index)
Index(['a', 'b', 'c'], dtype='object')

print (finaldf1.index.name)
None

print (finaldf1.columns.name)
District

For column is necessary DataFrame.rename_axis with DataFrame.reset_index :

df.index = pd.Index(['Active','Confirmed','Deceased','Recovered'],name='District') 


finaldf=df.T.rename_axis(index='District', columns=None).reset_index()
print (finaldf)
  District    Active  Confirmed  Deceased  Recovered
0        a  0.700793   0.722742  0.452414   0.507035
1        b  0.669347   0.853931  0.296660   0.370256
2        c  0.552846   0.609019  0.630620   0.138213  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM