astype转换数据类型
astype方法:通用函数,可以用于把dataframe中的任何列转换成其他类型常见的数据类型有:int 整型;float 浮点型;object/str 字符串;category 分类数据。import pandas as pdimport seaborn as snstips=sns.load_dataset('tips')#选择seaborn自带数据集中的tipsprint(tips.dtyp
astype方法:通用函数,可以用于把dataframe中的任何列转换成其他类型
常见的数据类型有:int 整型;float 浮点型;object/str 字符串;category 分类数据。
import pandas as pd
import seaborn as sns
tips=sns.load_dataset('tips')#选择seaborn自带数据集中的tips
print(tips.dtypes)#查看tips数据每一列的类型
tips['sex']=tips['sex'].astype(str)#将sex列转换成字符串类型并赋值给sex列
print(tips.dtypes)
tips['sex_str']=tips['sex'].astype(str)#将sex列转换成字符串类型并赋值给新列
print(tips.dtypes)
输出结果如下:
total_bill float64
tip float64
sex category
smoker category
day category
time category
size int64
dtype: object
[Finished in 1.8s]total_bill float64
tip float64
sex object
smoker category
day category
time category
size int64
dtype: object
[Finished in 1.7s]total_bill float64
tip float64
sex category
smoker category
day category
time category
size int64
sex_str object
dtype: object
[Finished in 1.7s]
更多推荐
所有评论(0)