Reputation: 79
I am using jupyter notebook and getting data using API.
I have a list of names.
names = ['a','b','c','d']
for name in names:
df=library.function(name)
print(df)
Then I get multiple dictionaries.
{'name':'a', 'level':2, 'quality': 12}
{'name':'b', 'level':3, 'quality': 14}
{'name':'c', 'level':6, 'quality': 13}
{'name':'d', 'level':2, 'quality': 11}
The dictionaries are not defined as something like dict_1 ~ dict_4 or these are not a list of multiple dictionaries, so I have no idea what to do :( Is there any way that I can change/merge these multiple dictionaries to a pandas dataframe?
Thanks in advance!
Upvotes: 1
Views: 759
Reputation: 18306
You can put dictionaries into a list in the loop and then cast to a DataFrame:
dicts_list = [] # to hold the dictionaries
names = ["a", "b", "c", "d"]
for name in names:
new_dict = library.function(name)
dicts_list.append(new_dict) # store it
# make a frame
data_frame = pd.DataFrame(dicts_list)
to get
>>> data_frame
name level quality
0 a 2 12
1 b 3 14
2 c 6 13
3 d 2 11
But this "make a list - turn a loop - append to it" calls for list comprehension, so:
dicts_list = [library.function(name) for name in names]
data_frame = pd.DataFrame(dicts_list)
You can also skip the intermediary variable dicts_list
:
data_frame = pd.DataFrame([library.function(name) for name in names])
Lastly, you can even drop the []
to make it a generator!
data_frame = pd.DataFrame(library.function(name) for name in names)
All give the same result.
Upvotes: 2
Reputation: 860
you can add a list and it will create for you automatic data frame
import pandas as pd
list_t =[
{'name':'a', 'level':2, 'quality': 12},
{'name':'b', 'level':3, 'quality': 14},
{'name':'c', 'level':6, 'quality': 13},
{'name':'d', 'level':2, 'quality': 11}
]
pd.DataFrame(list_t)
#output
name level quality
0 a 2 12
1 b 3 14
2 c 6 13
3 d 2 11
Upvotes: 1