Python Pandas DataFrame.astype()

Python Pandas DataFrame.astype()

Python是一种进行数据分析的伟大语言,主要是因为以数据为中心的Python包的奇妙生态系统。Pandas就是这些包中的一个,它使导入和分析数据变得更加容易。

DataFrame.astype()方法用于将pandas对象投向指定的dtype。 astype()函数还提供了将任何合适的现有列转换为分类类型的能力。

DataFrame.astype()函数在我们想把一个特定的列数据类型变成另一个数据类型时非常方便。不仅如此,我们还可以使用Python字典输入,一次改变多个列的类型。dictionary中的key标签对应于列名,dictionary中的values标签对应于我们希望列成为的新数据类型。

语法: DataFrame.astype(dtype, copy=True, errors=’raise’, **kwargs)

参数:
dtype : 使用numpy.dtype或Python类型来将整个pandas对象转换为同一类型。或者,使用{col: dtype, …},其中col是一个列标签,type是numpy.dtype或Python类型,将DataFrame的一个或多个列转换为特定的列类型。
copy : 当copy=True时返回一个副本(设置copy=False时要非常小心,因为对数值的改变可能会传播到其他pandas对象上)。

errors : 控制对所提供的dtype的无效数据引发的异常。
raise : 允许提出异常情况
ignore : 抑制异常。出错时返回原始对象

kwargs :传递给构造函数的关键字参数。

返回: casted:调用者的类型

例子#1:转换Weight列的数据类型。

# importing pandas as pd
import pandas as pd
  
# Making data frame from the csv file
df = pd.read_csv("nba.csv")
  
# Printing the first 10 rows of 
# the data frame for visualization
  
df[:10]
Python

Python Pandas DataFrame.astype()

由于数据中有一些 “纳米 “值,为了避免任何错误,我们将放弃所有含有纳米值的行。

# drop all those rows which 
# have any 'nan' value in it.
df.dropna(inplace = True)
Python

Python Pandas DataFrame.astype()

# let's find out the data type of Weight column
before = type(df.Weight[0])
  
# Now we will convert it into 'int64' type.
df.Weight = df.Weight.astype('int64')
  
# let's find out the data type after casting
after = type(df.Weight[0])
  
# print the value of before
before
  
# print the value of after
after
Python

输出:
Python Pandas DataFrame.astype()
Python Pandas DataFrame.astype()

# print the data frame and see
# what it looks like after the change
df
Python

Python Pandas DataFrame.astype()

例子2:一次改变多于一列的数据类型

将姓名列改为分类类型,年龄列改为int64类型。

# importing pandas as pd
import pandas as pd
  
# Making data frame from the csv file
df = pd.read_csv("nba.csv")
  
# Drop the rows with 'nan' values
df = df.dropna()
  
# print the existing data type of each column
df.info()
Python

输出:
Python Pandas DataFrame.astype()

现在让我们一次改变两列的数据类型。

# Passed a dictionary to astype() function 
df = df.astype({"Name":'category', "Age":'int64'})
  
# Now print the data type 
# of all columns after change
df.info()
Python

输出:
Python Pandas DataFrame.astype()

# print the data frame
# too after the change
df
Python

输出:
Python Pandas DataFrame.astype()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册