Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 610
tensor Avatar asked Dec 11 '16 15:12

tensor


People also ask

How do you get Dtypes pandas?

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.

How do I convert a pandas DataFrame to a dictionary?

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.

Can a pandas column be a dictionary?

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.

Can you create a series from the dictionary object in pandas?

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.


1 Answers

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'}
like image 179
ayhan Avatar answered Sep 24 '22 20:09

ayhan