Home > OS >  Python dataframe to dictionary (keys: position of the column, value the names of the variables of th
Python dataframe to dictionary (keys: position of the column, value the names of the variables of th

Time:10-24

I need to create a dictionary whose keys contain the position of the column and the value the names of the variables of the dataframe.

DataFrame:

    ID   A   B   C
0   p    1   3   2
1   q    4   3   2
2   r    4   0   9  

Output should be like this:

Dictionary = {'1': [ID], '2': [A], '3': [B],'4': [C]}

CodePudding user response:

Use enumerate with dict comprehension - create strings keys and one element lists:

d = {str(k): [v] for k, v in enumerate(df.columns, 1)}
print (d)
{'1': ['ID'], '2': ['A'], '3': ['B'], '4': ['C']}

Or if need intgers without lists use:

d1 = dict(enumerate(df.columns, 1))
print (d1)
{1: 'ID', 2: 'A', 3: 'B', 4: 'C'}

CodePudding user response:

Use Index.to_series() Series.items() to iterate on index, value information.

# You should set the index of the new serie using the index optional parameter, 
# this will be an iterable from 1 to len(columns)   1
serie = df.columns.to_series(index=range(1, len(df.columns) 1))
d = {index: [value] for index, value in serie}

Or, if you prefer one-line solution:

d = {index: [value] for index, value in df.columns.to_series(index=range(1, len(df.columns) 1)).items()}

Output:

{1: ['ID'], 2: ['A'], 3: ['B'], 4: ['C']}
  • Related