I am trying to take data from a pandas dataframe and transform it to a desired dictionary. Here's an example of the data:
data =[[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1],[0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2]]
Utable = pd.DataFrame(data, columns =['Type1', 'Type2', 'Type3', 'Type4', 'Type5', 'Type6', 'Type7', 'Type8', 'ID'])
The dictionary I need is the ID records as the dict key and the values need to be a list of the unacceptable Type #s ascertained from the column name. The Types are unacceptable if they are 0.0. So for this example the output would be:
{1: [1, 2, 3, 4, 5, 6, 7, 8], 2: [1, 2, 4, 5, 6, 7, 8]}
I could figure out how to get the type values stored as list with the ID as the dict key using:
U = Utable.set_index('ID').T.to_dict('list')
which gives:
{1: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 2: [0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]}
but I can't figure out how to get the contents from the column name stored in the list as the dict values.
Thanks very much for any help.
CodePudding user response:
You could use the parameter orient=index
when converting to a dictionary; then use a list comprehension to get the desired list as values:
out = {k: [int(i[-1]) for i, v in d.items() if v==0]
for k, d in Utable.set_index('ID').to_dict('index').items()}
Output:
{1: [1, 2, 3, 4, 5, 6, 7, 8], 2: [1, 2, 4, 5, 6, 7, 8]}