The data type correspondence in Python and in Pandas is as follows:
- Fruit data is pure data that can be converted into numbers
- asype is basically used as two kinds of numbers into simple strings, simple strings into numbers, containing other non-numeric strings can not be converted by asype.
- Other methods need to be introduced for the transformation, which also results in the following custom function methods
astype() is the most common and versatile data type conversion method
import pandas as pd df = ([['liver','E',89,21,24,64], ['Arry','C',36,37,37,57], ['Ack','A',57,60,18,84], ['Eorge','C',93,96,71,78], ['Oah','D',65,49,61,86] ], columns = ['name','team','Q1','Q2','Q3','Q4']) res = df.('int32').dtypes # dtype('int32') ({'Q1':'int32','Q2':'int32'}).dtypes
Results Showcase
df
res
extensions
# The following are some examples of use. ('int64') # Index type conversion ('int32') # All data converted to int32 ({'col1':'int32'}) # Specified fields to specified types ('int64') ('int64',copy = False) # Not associated with original data df['name'].astype('object') data['Q4'].astype('float') ('datatime64[ns]') # Converted to time type data['Status'].astype('bool')
data type
will return the data type of each field and the type of the DataFrame as a whole
If it's a Series, you need to use the
import pandas as pd df = ([['liver','E',89,21,24,64], ['Arry','C',36,37,37,57], ['Ack','A',57,60,18,84], ['Eorge','C',93,96,71,78], ['Oah','D',65,49,61,86] ], columns = ['name','team','Q1','Q2','Q3','Q4']) s = (['One','Two','Three'])
Results Showcase
df
s
When the format of the data does not have the conditions for conversion to the target type, the data needs to be processed first
For example, "89.3%" is a string that is converted to a number by removing the percent sign.
# Convert text such as "89.3%" to a floating point number (lambda x:('%','')).astype('float')/100
When loading data, you can specify the type of each column of the data.
import pandas as pd # Assign uniform types to all fields df = (data, dtype = 'float32') # Specify each field separately df = pd.read_excel(data, dtype = {'team':'string','Q1':'int32'})
to this article on the realization of the Pandas type conversion asype () article is introduced to this, more related Pandas type conversion asype () content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future !