简体   繁体   中英

Pandas create Dataframe with index name as column name

I have an existing dataframe with column name and data. I want to change index.name for dataframe to be column's name. I am confused about multi - indexing how do I do that? Because then I need to pass that dataframe to the to_sql function which considers index as name of column for table.

Currently for me dataframe.index is RangeIndex(start=0, stop=1669, step=1)

and dataframe.index.name is None

I have done as follows :

dataframe.index.names = dataframe.columns
dataframe = dataframe.rename_axis(dataframe.columns)

It's giving me error as Length of new names must be 1, got 67 . 67 is number of column I have in dataframe.

It depends if MultiIndex or not.

For single index need:

df.index.name = 'foo'
df = df.rename_axis('foo')

For MultiIndex need:

df.index.names = ('foo', 'bar')
df = df.rename_axis(('foo', 'bar'))

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