4

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

4 Answers 4

3

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)
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

You can use loop like this:

myList = list(df.columns)
index = 0

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

Comments

1

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.