Reputation: 1251
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...
Upvotes: 6
Views: 8434
Reputation: 59519
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
Upvotes: 4
Reputation: 79
Not sure exactly your rules of selecting objects from the list of values.. so I just made a random selection here. But the idea should be similar:
value_list = np.random.rand(1000).tolist()
df = pd.DataFrame()
for i in range(10, 101, 10):
a, b, c = random.sample(value_list, 3)
df.loc[i, 'key1'] = a
df.loc[i, 'key2'] = b
df.loc[i, 'key3'] = c
Upvotes: 0