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?
To check the data type in pandas DataFrame we can use the “dtype” attribute. The attribute returns a series with the data type of each column. And the column names of the DataFrame are represented as the index of the resultant series object and the corresponding data types are returned as values of the series object.
Use DataFrame. To convert pandas DataFrame to Dictionary object, use to_dict() method, this takes orient as dict by default which returns the DataFrame in format {column -> {index -> value}} . When no orient is specified, to_dict() returns in this format.
Pandas Columns to Dictionary with Pandas' to_dict() function It is a versatile function to convert a Pandas dataframe or Series into a dictionary. In most use cases, Pandas' to_dict() function creates dictionary of dictionaries. It uses column names as keys and the column values as values.
You can create a pandas series from a dictionary by passing the dictionary to the command: pandas. Series() . In this article, you will learn about the different methods of configuring the pandas.
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With