简体   繁体   中英

Transfer pandas dataframe column names to dictionary

I'm trying to convert a pandas dataframe column names into a dictionary. Not so worried about the actual data in the dataframe.

Say I have an example dataframe like this and I'm not too worried about index just now:

Col1 Col2 Col3 Col4
--------------------
 a    b    c    a
 b    d    e    c

I'd like to get an output of a dictionary like:

{'Col1': 0, 'Col2': 1, 'Col3': 2, 'Col4': 3}

Not too worried about the order they get printed out, as long as the assigned keys in the dictionary keep the order for each column name's order.

That is straight forward with a comprehension as:

Code:

{c: i for i, c in enumerate(df.columns)}

Test Code:

import pandas as pd

df = pd.DataFrame({'date': ['2015-01-01', '2015-01-02', '2015-01-03'],
                   'value': ['a', 'b', 'c'],
                   'num': [1, 2, 3]
                   })

print(df)
print({c: i for i, c in enumerate(df.columns)})

Results:

         date  num value
0  2015-01-01    1     a
1  2015-01-02    2     b
2  2015-01-03    3     c

{'date': 0, 'num': 1, 'value': 2}

Instead of using enumerate as @StephenRauch has posted, you could also use a pandas.Index method, get_loc :

{i:df.columns.get_loc(i) for i in df.columns}

Using Stephen's setup:

import pandas as pd

df = pd.DataFrame({'date': ['2015-01-01', '2015-01-02', '2015-01-03'],
                   'value': ['a', 'b', 'c'],
                   'num': [1, 2, 3]
                   })

print(df)
print({i:df.columns.get_loc(i) for i in df.columns})

Output:

         date value  num
0  2015-01-01     a    1
1  2015-01-02     b    2
2  2015-01-03     c    3

{'date': 0, 'value': 1, 'num': 2}

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