Search code examples
pythonpandasdataframedictionarydata-analysis

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.


Solution

  • 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}