Home > Mobile >  Get column names with corresponding index in python pandas
Get column names with corresponding index in python pandas

Time:02-17

I have this dataframe df where

>>> df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/11'],
                    'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],
                    'Cost':[10000, 5000, 15000, 2000],
                    'Name':['Roy', 'Abraham', 'Blythe', 'Sophia'],
                    'Age':['20', '10', '13', '17']})

I want to determine the column index with the corresponding name. I tried it with this:

>>> list(df.columns)

But the solution above only returns the column names without index numbers.

How can I code it so that it would return the column names and the corresponding index for that column? Like This:

0 Date
1 Event
2 Cost
3 Name
4 Age

CodePudding user response:

A nice short way to get a dictionary:

d = dict(enumerate(df))

output: {0: 'Date', 1: 'Event', 2: 'Cost', 3: 'Name', 4: 'Age'}

For a Series, pd.Series(list(df)) is sufficient as iteration occurs directly on the column names

CodePudding user response:

Simpliest is add pd.Series constructor:

pd.Series(list(df.columns))

Or convert columns to Series and create default index:

df.columns.to_series().reset_index(drop=True)

Or:

df.columns.to_series(index=False)

CodePudding user response:

In addition to using enumerate, this also can get a numbers in order using zip, as follows:

import pandas as pd
df = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/11'],
                    'Event':['Music', 'Poetry', 'Theatre', 'Comedy'],
                    'Cost':[10000, 5000, 15000, 2000],
                    'Name':['Roy', 'Abraham', 'Blythe', 'Sophia'],
                    'Age':['20', '10', '13', '17']})

result = list(zip([i for i in range(len(df.columns))], df.columns.values,))

for r in result:
    print(r)

#(0, 'Date')
#(1, 'Event')
#(2, 'Cost')
#(3, 'Name')
#(4, 'Age')

CodePudding user response:

You can use loop like this:

myList = list(df.columns)
index = 0

for value in myList:
     print(index, value)
     index  = 1
  • Related