I have a little issue with my the data I have (multiple dictionaries) to process and create a Dataframe from them. At the moment I'm a beginner so I'm struggling to make this happen.
This what the data look like:
print(data)
0 {'john': True}
1 {'joe': True}
2 {'tom': True}
3 {'mark': False}
4 {'andrew': True}
...
93 {'david': False}
94 {'luke': False}
95 {'vincent': True}
96 {'oliver': True}
97 {'matthew': True}
Length: 98, dtype: object
Basically what I want is this:
df = pd.DataFrame()
df['name'] = data[0].keys()
df['result'] = data[0].values()
print(df)
name result
0 john True
So 1 dataframe with 2 columns - name and result.
How can I apply that procedure for all dictionaries in data and have 1 output in the same Dataframe? I was not able to replicate that action via lambda function, but maybe I was not doing it right.
Thanks in advance for all advices
CodePudding user response:
pd.DataFrame(data.apply(lambda x: list(x.items())[0]).values.tolist())
you can rename columns, using:
df.rename(columns={0: 'name', 1: 'result'}, inplace=True)
CodePudding user response:
You can save the keys and the values of your dictionaries in lists, and then create your DataFrame from them. There is probably a better way to do it but it works!
import pandas as pd
data = [{'john': True}, {'joe': True}, {'tom': True}, {'mark': False}, {'andrew': True}, {'david': False}, {'luke': False}]
names = []
results = []
for dict1 in data:
name = list(dict1.keys())[0]
result = list(dict1.values())[0]
names.append(name)
results.append(result)
df = pd.DataFrame(zip(names, results), columns=["name", "result"])
print(df)
Output
name result
0 john True
1 joe True
2 tom True
3 mark False
4 andrew True
5 david False
6 luke False