tensor
tensor

Reputation: 3350

Is there a way to generate the dtypes as a dictionary in pandas?

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?

Upvotes: 24

Views: 31845

Answers (1)

user2285236
user2285236

Reputation:

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')}

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'}

Upvotes: 62

Related Questions