Python是进行数据分析的一种出色语言,主要是因为以数据为中心的python软件包具有奇妙的生态系统。 Pandas是其中的一种,使导入和分析数据更加容易。
DataFrame.astype()方法用于将pandas对象转换为指定的dtype。astype()函数还提供了将任何合适的现有列转换为分类类型的函数。
DataFrame.astype()当我们想将特定的列数据类型转换为另一种数据类型时,该函数非常方便。不仅如此,我们还可以使用Python字典输入一次更改多个列类型。字典中的键标签与列名相对应,字典中的值标签与我们希望列属于的新数据类型相对应。
用法: DataFrame.astype(dtype, copy=True, errors=’raise’, **kwargs)
参数:
dtype:用一个numpy.dtype 或Python类型将整个pandas对象转换为相同类型。或者,使用{col:dtype,…},其中col是列标签,而dtype是numpy.dtype或Python类型,以将DataFrame的一个或多个列转换为column-specific类型。
copy:当copy = True时返回一个副本(要非常小心,将copy = False设置为数值的更改,然后可能会传播到其他 Pandas 对象)。
errors:控制针对提供的dtype的无效数据引发异常。
引发:允许引发异常
忽略:禁止异常。错误返回原始对象
kwargs:keyword参数传递给构造函数
返回值:演员:来电者类型
有关在代码中使用的CSV文件的链接,请单击此处
范例1:转换“权重”列数据类型。
# 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]
由于数据具有一些“nan”值,因此,为了避免出现任何错误,我们将删除所有包含以下内容的行nan 值。
# drop all those rows which  
# have any 'nan' value in it. 
df.dropna(inplace = True)
# 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输出:


# print the data frame and see 
# what it looks like after the change 
df
范例2:一次更改多于一列的数据类型
改变Name 列到分类类型和Age 列为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()输出:

现在,我们一次更改两个列的数据类型。
# 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()输出:

# print the data frame 
# too after the change 
df输出:

相关用法
- Python pandas.map()用法及代码示例
- Python Pandas Timestamp.tz用法及代码示例
- Python Pandas Series.str.contains()用法及代码示例
- Python Pandas dataframe.std()用法及代码示例
- Python Pandas Timestamp.dst用法及代码示例
- Python Pandas dataframe.sem()用法及代码示例
- Python Pandas DataFrame.ix[ ]用法及代码示例
- Python Pandas.Categorical()用法及代码示例
- Python Pandas.apply()用法及代码示例
- Python Pandas TimedeltaIndex.contains用法及代码示例
- Python Pandas Timestamp.now用法及代码示例
- Python Pandas Series.str.pad()用法及代码示例
- Python Pandas Series.take()用法及代码示例
- Python Pandas dataframe.all()用法及代码示例
- Python Pandas series.str.get()用法及代码示例
注:本文由纯净天空筛选整理自Shubham__Ranjan大神的英文原创作品 Python | Pandas DataFrame.astype()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
