I have a function that returns a dictionary of keys and results.
I'd like to create a new function that loops through different values. Each value would produce a new dictionary of different result but with the same keys.
I'd like to have this function create a dataframe and with each iteration through the loop, the index (or first column) is set to the i value of my loop and the row would be the resulting dictionary. .
the dictionary would look like {key1: 46, key2:100,key3:200}
start = 10
stop = 100
step = 10
the final result would look something like:
key1 key2 key3
10 46 100 200
20 50 75 60
30 80 2 10
40 100 50 6
50 10 8 33
etc...
concat() by creating a new dataframe of all the rows that we need to add and then appending this dataframe to the original dataframe.
You can use the df. loc() function to add a row to the end of a pandas DataFrame: #add row to end of DataFrame df. loc[len(df.
A pandas DataFrame can be converted into a Python dictionary using the DataFrame instance method to_dict(). The output can be specified of various orientations using the parameter orient. In dictionary orientation, for each column of the DataFrame the column value is listed against the row label in a dictionary.
Create a nested dictionary of the value and the dictionary the function returns, and then use the DataFrame constructor from_dict
with orient='index'
at the very end.
import pandas as pd
import numpy as np
np.random.seed(123)
start = 10
stop = 100
step = 10
d2 = {}
while start <= stop:
# Simulating your function that returns a dictionary:
d = {'key1': np.random.randint(1,100),
'key2': np.random.randint(1,10),
'key3': np.random.randint(20,70)}
# Add that dictionary to a dictionary
d2[start] = d
start+=step
pd.DataFrame.from_dict(d2, orient='index')
Output:
key1 key2 key3
10 67 3 58
20 18 4 62
30 58 7 53
40 97 2 67
50 74 1 66
60 97 4 34
70 37 1 36
80 69 2 23
90 3 5 59
100 67 5 67
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With