Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a Dictionary as a new row in a data frame

Tags:

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...
like image 631
novawaly Avatar asked Aug 22 '18 19:08

novawaly


People also ask

Which method is used to add new row in a data frame?

concat() by creating a new dataframe of all the rows that we need to add and then appending this dataframe to the original dataframe.

How do you create a row in a data frame?

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.

Can you put a dictionary in a Pandas DataFrame?

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.


1 Answers

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
like image 55
ALollz Avatar answered Sep 28 '22 17:09

ALollz