Reputation: 928
I have the following input:
{'1LsquDfKDtz1uFz7txAVixkgFc82PHwqqp': {"balance": 0}, '1FBGyQnLZrfwVZRdYNxbrqnKukm9trH5Ka': {"balance": 0}, '1DSBqLVtDFgMypdo2yC77C5LZuTCHZS7St': {"balance": 34},
...
That I would like to put in a a dataframe. But I run the code:
p = pd.DataFrame.from_dict(input)
I got the error:
ValueError: If using all scalar values, you must pass an index
Expected output in xlsx:
addresse balance
'1LsquDfKDtz1uFz7txAVixkgFc82PHwqqp' 0
'1FBGyQnLZrfwVZRdYNxbrqnKukm9trH5Ka' 0
'1DSBqLVtDFgMypdo2yC77C5LZuTCHZS7St' 34
Any contribution would be appreciated.
Upvotes: 1
Views: 35
Reputation: 862741
Add parameter orient='index'
to DataFrame.from_dict
, then create index name by DataFrame.rename_axis
and last convert index to column by DataFrame.reset_index
:
d = {'1LsquDfKDtz1uFz7txAVixkgFc82PHwqqp': {"balance": 0},
'1FBGyQnLZrfwVZRdYNxbrqnKukm9trH5Ka': {"balance": 0},
'1DSBqLVtDFgMypdo2yC77C5LZuTCHZS7St': {"balance": 34}}
p = pd.DataFrame.from_dict(d, orient='index').rename_axis('addresse').reset_index()
print (p)
addresse balance
0 1DSBqLVtDFgMypdo2yC77C5LZuTCHZS7St 34
1 1FBGyQnLZrfwVZRdYNxbrqnKukm9trH5Ka 0
2 1LsquDfKDtz1uFz7txAVixkgFc82PHwqqp 0
Another idea is use list comprehension and prepend new key to list of dictionaries, last pass to DataFrame
constructor:
p = pd.DataFrame([dict(**{'addresse':k}, **v) for k, v in d.items()])
print (p)
addresse balance
0 1LsquDfKDtz1uFz7txAVixkgFc82PHwqqp 0
1 1FBGyQnLZrfwVZRdYNxbrqnKukm9trH5Ka 0
2 1DSBqLVtDFgMypdo2yC77C5LZuTCHZS7St 34
Upvotes: 1
Reputation: 1883
Alternative code:
Using .from_dict()
, .stack()
, .unstack()
and .reset_index()
. Modified the code posted in the question.
# Import libraries
import pandas as pd
# Create dictionary
d = {'1LsquDfKDtz1uFz7txAVixkgFc82PHwqqp': {"balance": 0},
'1FBGyQnLZrfwVZRdYNxbrqnKukm9trH5Ka': {"balance": 0},
'1DSBqLVtDFgMypdo2yC77C5LZuTCHZS7St': {"balance": 34}
}
# Create DataFrame from dictionary
df = pd.DataFrame.from_dict(d).stack().unstack(0).reset_index()
# Rename columns
df.columns = ['address', 'balance']
Output
print(df)
address balance
0 1LsquDfKDtz1uFz7txAVixkgFc82PHwqqp 0
1 1FBGyQnLZrfwVZRdYNxbrqnKukm9trH5Ka 0
2 1DSBqLVtDFgMypdo2yC77C5LZuTCHZS7St 34
Upvotes: 0