Reputation: 1939
I have a dictionary like so:
d = {
'2020-07-27': {'distinct_ntwrk_cd': 127, 'distinct_inv_type_cd': 44, 'distinct_syscode': 679},
'2020-07-28': {'distinct_ntwrk_cd': 124, 'distinct_inv_type_cd': 43, 'distinct_syscode': 678}
}
And would like to convert it to a pandas dataframe like so:
Date | distinct_ntwrk_cd | distinct_inv_type_cd | distinct_syscode |
---|---|---|---|
2020-07-27 | 127 | 44 | 679 |
2020-07-28 | 124 | 43 | 678 |
Doesn't matter to me if the date is the index or not. What is the easiest way to do this?
Upvotes: 1
Views: 1788
Reputation: 26676
Please try
df = pd.DataFrame(d).T
distinct_ntwrk_cd distinct_inv_type_cd distinct_syscode
2020-07-27 127 44 679
2020-07-28 124 43 678
Upvotes: 2
Reputation: 95
I think the answer posted by @Quang is best solution, till now However, if you wanna try an alternative:
data = [['Date','distinct_ntwrk_cd','distinct_inv_type_cd','distinct_syscode']];
for k,v in d.items():
indices=[]
indices.append(k)
vals=[]
for k1,v1 in v.items():
indices.append(v1)
data.append(indices)
df = pd.DataFrame(data[1:],columns=data[0]); df
Upvotes: 0
Reputation: 21
You can simply put the dict into the pandas DataFrame method and then swap the columns and rows using the transpose method
import pandas as pd
df = pd.DataFrame(d).T
Upvotes: 1
Reputation: 150735
With date
being index, you can just do:
df = pd.DataFrame(d).T
You can further try rename the index, and chain with reset_index
to make date
a normal column:
pd.DataFrame(d).T.rename_axis('Date').reset_index()
Output:
Date distinct_ntwrk_cd distinct_inv_type_cd distinct_syscode
0 2020-07-27 127 44 679
1 2020-07-28 124 43 678
Upvotes: 4