有没有办法在 pandas 中将dtypes生成为字典? [英] Is there a way to generate the dtypes as a dictionary in pandas?
本文介绍了有没有办法在 pandas 中将dtypes生成为字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
键入df.dtypes
时,我们具有类型列表.
但是,有没有一种简单的方法可以将输出获取为
When typing df.dtypes
, we have the list of types.
However, is there a simple way to get the output as
{'col1': np.float32, ...}
还是我需要自己编写一个函数?
or do I need to code a function myself?
推荐答案
df.dtypes
的类型返回对象是pandas.Series.它具有to_dict
方法:
The type returning object of df.dtypes
is pandas.Series. It has a to_dict
method:
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:
The values in the dictionary are from dtype class. If you want the names as strings, you can use apply:
df.dtypes.apply(lambda x: x.name).to_dict()
Out: {'A': 'int64', 'B': 'float64', 'C': 'object', 'D': 'bool'}
这篇关于有没有办法在 pandas 中将dtypes生成为字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文