Efficient way of looping through list of dictionaries and appending items into column in dataframe
One idea is pass data
to DataFrame
cosntructor and then use rename
:
df = pd.DataFrame(data).rename(columns={'1':'col1'})
print (df)
col1
0 20
1 10
2 40
3 14
4 33
If is necessary filtering use list comprehension and add parameter columns
:
df = pd.DataFrame([x['1'] for x in data], columns=['col1'])
print (df)
col1
0 20
1 10
2 40
3 14
4 33
EDIT: For new data use:
data = [
{'1':
{'value':20}},
{'1':
{'value':10}},
{'1':
{'value':40}},
{'1':
{'value':14}},
{'1':
{'value':33}}]
df = pd.DataFrame([x['1']['value'] for x in data], columns=['col1'])
print (df)
col1
0 20
1 10
2 40
3 14
4 33
Or:
df = pd.DataFrame([x['1'] for x in data]).rename(columns={'value':'col1'})
print (df)
col1
0 20
1 10
2 40
3 14
4 33
@jezrael's answer is correct but to be more specific with col
:
df = pd.DataFrame(data)
print(df.add_prefix('col'))
Output:
col1
0 20
1 10
2 40
3 14
4 33