当输入df.dtypes时,我们有类型列表。
但是,是否有一种简单的方法可以将输出作为

{'col1': np.float32, ...}

或者我需要自己编写函数代码吗?

最佳答案

df.dtypes的类型返回对象是pandas.series。它有一个to_dict方法:

df = pd.DataFrame({'A': [1, 2],
                   'B': [1., 2.],
                   'C': ['a', 'b'],
                   'D': [True, False]})

df
Out:
   A    B  C      D
0  1  1.0  a   True
1  2  2.0  b  False

df.dtypes
Out:
A      int64
B    float64
C     object
D       bool
dtype: object

df.dtypes.to_dict()
Out:
{'A': dtype('int64'),
 'B': dtype('float64'),
 'C': dtype('O'),
 'D': dtype('bool')}

字典中的值来自DTYPE类。如果要将名称作为字符串,可以使用Apply:
df.dtypes.apply(lambda x: x.name).to_dict()
Out: {'A': 'int64', 'B': 'float64', 'C': 'object', 'D': 'bool'}

关于python - 有没有办法在dandas中生成dtypes作为字典?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41087887/

10-11 22:01