What is the preferred way to convert dictionary of dictionaries into a data frame with data types?
I have the following kind of dictionary r
which contains fact sets behind each key
import pandas as pd
r = { 1:{'a':1,'b':2,'c':'b'},
2:{'d':1,'b':1,'c':'b'},
3:{'e':0} }
Converting this dictionary of dictionaries into a dataframe can be done in a quite straightforward way
x = pd.DataFrame(r)
x
x.dtypes
which yields the following version on the original dictionary of dictionaries
1 2 3
a 1 NaN NaN
b 2 1 NaN
c b e NaN
d NaN 1 NaN
e NaN NaN 0.0
and the following datatypes for columns
1 object
2 object
3 float64
dtype: object
However, I would like to have transposed version on x
. After doing so
y = x.transpose()
y
y.dtypes
it seems like the expected representation on the data is shown in matrix form
a b c d e
1 1 2 b NaN NaN
2 NaN 1 e 1 NaN
3 NaN NaN NaN NaN 0
but the data types are all object
a object
b object
c object
d object
e object
dtype: object
What is the preferred way to do such conversion from r
to y
so that y.dtypes
would yield directly data types
a float64
b float64
c object
d float64
e float64
dtype: object
similar to converting r
to x
?
Just set the right orientation (default is columns
, you want index
).
df = pd.DataFrame.from_dict(r, orient='index')
a float64
b float64
c object
d float64
e float64
dtype: object