pandas 轻松实现数据类型转化

  首先,了解一下pandas的数据类型:

Pandas dtypePython typeNumPy typeUsage
objectstr or mixedstring_, unicode_, mixed typesText or mixed numeric and non-numeric values
int64intint_, int8, int16, int32, int64, uint8, uint16, uint32, uint64Integer numbers
float64floatfloat_, float16, float32, float64Floating point numbers
boolboolbool_True/False values
datetime64NAdatetime64[ns]Date and time values
timedelta[ns]NANADifferences between two datetimes
categoryNANAFinite list of text values

Notes:object在加载数据时可以处理任何其他数据类型,包括字符串,所以在pandas新版本1.0.0中新增了一数据类型,StringDtype,,专用来处理字符串。也算是一个改进。

两个重要的数据转化方法
1、astype

DataFrame.astype(dtype, copy = True, errors = 'raise') 
or
Series.astype(dtype, copy = True, errors = 'raise') 

上述方法可以将一类数据转换类型或者传入一个dict,列为key,需要转化的数据类型为value。

2、convert_dtypes

DataFrame.convert_dtypes(infer_objects = True, convert_string:  True, convert_integer = True, convert_boolean = True)
or
Series.convert_dtypes(infer_objects = True, convert_string:  True, convert_integer = True, convert_boolean = True)

convert_dtypes可以自动推断数据类型并进行转化。个人感觉,这个方法只在识别string上智能,在int推断时还是会尽可能的选择大高位存储,int还是以int64为主,内存消耗还是很大。
举例:

df = pd.DataFrame({'a':[1,2,3],'b':[0.55,0.66,1.55],'c':['Jack','Tony','Posi']})
df.dtypes
a      int64
b    float64
c     object
dtype: object
df['a'] = df['a'].astype(np.int32)
df.dtypes
a      int32
b    float64
c     object
dtype: object
df.convert_dtypes().dtypes
a      Int64
b    float64
c     string
dtype: object

参考:
https://pandas.pydata.org/pandas-docs/stable/getting_started/basics.html#basics-dtypes

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值