Create Nested Dict From Pandas Dataframe
I have a pandas dataframe that I would like to pull information from and create a nested dictionary for downstream use, however, I'm not very good at working with pandas yet and I
Solution 1:
You can use iterrows() to update a dictionary as-you-go:
iterrows() creates a tuple for each row, where the first element (i.e row[0]) is the row's index, and the 2nd element is a pd.Serie object for all the values in the row.
<input>
A_start A_end B_start B_end
sequence_1 0.1 0.025 0.030303 0.001
sequence_2 0.2 0.050 0.060606 0.002
sequence_3 0.3 0.075 0.090909 0.003
sequence_4 0.4 0.100 0.121212 0.004
A_value = 'some value'
B_value = 'other value'
d = dict()
for row in df.iterrows():
d[row[0]] = {(row[1]['A_start'], row[1]['A_end']): A_value, (row[1]['B_start'], row[1]['B_end']): B_value}
<output>
{'sequence_1': {(0.10000000000000001, 0.025000000000000001): 'some value', (0.030303030303030304, 0.001): 'other value'}}
Post a Comment for "Create Nested Dict From Pandas Dataframe"