有没有办法在 Pandas 中将 dtypes 生成为字典?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41087887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to generate the dtypes as a dictionary in pandas?
提问by tensor
When typing df.dtypes
, we have the list of types.
However, is there a simple way to get the output as
键入时df.dtypes
,我们有类型列表。但是,是否有一种简单的方法可以将输出作为
{'col1': np.float32, ...}
or do I need to code a function myself?
还是我需要自己编写一个函数?
回答by ayhan
The type returning object of df.dtypes
is pandas.Series. It has a to_dict
method:
的类型返回对象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')}
The values in the dictionary are from dtype class. If you want the names as strings, you can use apply:
字典中的值来自 dtype 类。如果要将名称作为字符串,可以使用 apply:
df.dtypes.apply(lambda x: x.name).to_dict()
Out: {'A': 'int64', 'B': 'float64', 'C': 'object', 'D': 'bool'}