0

I have a DataFrame named distinct_values:

   gender      purchase_frequency

0  Female                Low

1    Male                Mid

2    Male               High

3  Female                Mid

4  Female               High

5    Male                Low

I now want to convert each column of this dataframe into a dictionary where name of the dictionary is based on column name:

gender={'Female', 'Male', 'Male', 'Female', 'Female', 'Male'}
purchase_frequency= {'Low', 'Mid', 'High', 'Mid', 'High', 'Low'}

I have tried the following method but this combined the dataframe to a single dictionary of lists and that wasn't desired:

df_dict = dict(zip([i for i in distinct_values.columns] , [pd.DataFrame(distinct_values[i].unique(), columns=[i]) for i in distinct_values.columns]))

Please let me know if there is a solution to this

yatu
  • 86,083
  • 12
  • 84
  • 139
feyorn
  • 13
  • 3

1 Answers1

0
for col_name in distinct_values:
    exec(f'{col_name} = {dict(distinct_values[col_name])}')
print(gender)
print(purchase_frequency)

the result will be:
gender = {0: 'Female', 1: 'Male', 2: 'Male', 3: 'Female', 4: 'Female', 5: 'Male'}
purchase_frequency = {0: 'Low', 1: 'Mid', 2: 'High', 3: 'Mid', 4: 'High', 5: 'Low'}

Essi
  • 16