将字典字典转换为具有数据类型的数据框

时间:2020-10-20 16:35:12

标签: python pandas dataframe dictionary column-types

将字典词典转换为具有数据类型的数据框的首选方法是什么?

我有以下类型的词典r,其中每个键后面都包含事实集

import pandas as pd

r = { 1:{'a':1,'b':2,'c':'b'},
      2:{'d':1,'b':1,'c':'b'},
      3:{'e':0} }

可以很简单地将字典词典转换成数据框

x = pd.DataFrame(r)
x
x.dtypes

在原始字典中会产生以下版本

     1    2    3
a    1  NaN  NaN
b    2    1  NaN
c    b    e  NaN
d  NaN    1  NaN
e  NaN  NaN  0.0

以及以下列的数据类型

1     object
2     object
3    float64
dtype: object

但是,我想在x上转置版本。这样做之后

y = x.transpose()
y
y.dtypes

数据的预期表示形式似乎以矩阵形式显示

     a    b    c    d    e
1    1    2    b  NaN  NaN
2  NaN    1    e    1  NaN
3  NaN  NaN  NaN  NaN    0

但数据类型均为object

a    object
b    object
c    object
d    object
e    object
dtype: object

ry进行这种转换的首选方法是什么,以便y.dtypes将直接产生数据类型

a    float64
b    float64
c    object
d    float64
e    float64
dtype: object

类似于将r转换为x

2 个答案:

答案 0 :(得分:2)

只需设置正确的方向(默认为columns,您需要index)。

df = pd.DataFrame.from_dict(r, orient='index')

a    float64
b    float64
c     object
d    float64
e    float64
dtype: object

答案 1 :(得分:1)

pandas> = 1.0.0中,您可以使用.convert_dtypes()

>>> y.convert_dtypes().dtypes

a     Int64
b     Int64
c    string
d     Int64
e     Int64
dtype: object

请注意,这将使用新的pandas字符串类型,并且还将对丢失的值使用pd.NA。有一些参数会影响某些转换:

>>> y.convert_dtypes(convert_string=False).dtypes

a     Int64
b     Int64
c    object
d     Int64
e     Int64
dtype: object

如果您的pandas年龄较大,则可以将pd.to_numericapply一起使用,例如here

>>> y = y.apply(pd.to_numeric, errors='ignore') # for columns that fail, do nothing
>>> y.dtypes

a    float64
b    float64
c     object
d    float64
e    float64
dtype: object

我看不到没有循环就在整个数据帧上强制数字类型的方法(.astype()似乎不起作用,因为错误会导致整个转换失败,或者如果被忽略,则返回原始值数据类型)。


我刚刚看到.transpose() addresses this point的文档:

当DataFrame具有混合的dtypes时,我们将得到一个对象dtype为转置的DataFrame:

转置混合类型的DatraFrame会返回对象类型的DataFrame。这是出于完整性而复制的示例:

d2 = {'name': ['Alice', 'Bob'],
      'score': [9.5, 8],
      'employed': [False, True],
      'kids': [0, 0]}
df2 = pd.DataFrame(data=d2)
df2_transposed = df2.transpose()

print(df2, df2.dtypes, df2_transposed, df2_transposed.dtypes, sep='\n\n')

输出:

    name  score  employed  kids
0  Alice    9.5     False     0
1    Bob    8.0      True     0

#dtypes as expected
name         object
score       float64
employed       bool
kids          int64
dtype: object

              0     1
name      Alice   Bob
score       9.5     8
employed  False  True
kids          0     0

#dtypes are now object
0    object
1    object
dtype: object

因此,如果要转换dtypes,则必须包括其他命令。