Jul-01-2021, 01:40 PM
(This post was last modified: Jul-01-2021, 01:40 PM by mikisDeWitte.)
Hello,
I need to create a nested dictionary like so:
d= {"ftsg2a_co422": {1: 'visited or contacted', 0: 'not visited not contacted'}}
this dictionary then goes to a function that sets value labels to an SPSS file.
The data comes from a database where these 0's and 1's can be a string.
When I execute the code below, I get
'1': 'promotor'
Is there a way where I can modify this groupby, cast the value to integer where possible, so that I get
1 : promotor
'rgDEU': 'Germany'
etc?
I hope my question makes sense...
Regards,
Mikis
I need to create a nested dictionary like so:
d= {"ftsg2a_co422": {1: 'visited or contacted', 0: 'not visited not contacted'}}
this dictionary then goes to a function that sets value labels to an SPSS file.
The data comes from a database where these 0's and 1's can be a string.
When I execute the code below, I get
'1': 'promotor'
Is there a way where I can modify this groupby, cast the value to integer where possible, so that I get
1 : promotor
'rgDEU': 'Germany'
etc?
I hope my question makes sense...
Regards,
Mikis
import pandas as pd #So all of this is read in from a database: var= ["ftq10a_bra1", "ftq10a_bra1", "ftq10a_bra1", "ftq10a_bra2", "ftq10a_bra2", "ftq10a_bra2", "d1ccode", "d1ccode"] value= ["1", "2", "3", "1", "2", "3", "rgDEU", "rgFRA"] label= ["promotor", "passive", "detractor", "promotor", "passive", "detractor", "Germany", "France"] data_tuples = list(zip(var,value, label)) column_labels = pd.DataFrame(data_tuples, columns=['var','value', 'label']) #This is what I need to modify, so that "1" becomes 1 d = {k: f.groupby('value')['label'].apply(lambda x: x.iloc[0]).to_dict() for k, f in column_labels.groupby('var')}