数据类型转换

数据集中的数据,有的是整数和浮点数类型,有的可能是字符串类型、布尔类型等,而数据分析和机器学习算法喜欢的是整数或者浮点数(统称“数值”)。如果数据集中出现非数值类型的数据,就需要对其进行适当转化。

常用方法
1.astype
Pandas是在数据科学中必知、必会的工具,对于数据类型转化他提供了一个直接的方法astype

  • dtype : data type, or dict of column name -> data type

  • copy : bool, default True

  • errors : {‘raise’, ‘ignore’}, default ‘raise’

    • raise : allow exceptions to be raised
    • ignore : suppress exceptions. On error return original object.

注: astype方法只能转化全部由数字组成的数据。

In:	import pandas as pd
	df = pd.DataFrame([{'col1':'a','col2':'1'},
                      {'col1':'b','col2':'2'}])
	df

Out:		col1	col2
		0	a		1
		1	b		2
	
In: df.dtypes

Out:	col1    object
		col2    object
		dtype: object

In: df['col2-int'] = df['col2'].astype(int)  
	df
Out:		col1	col2	col2-int
		0	a		1		1
		1	b		2		2

In: df.dtypes
Out:	col1        object
		col2        object
		col2-int     int32
		dtype: object

2.pd.to_numeric(arg, errors=‘raise’, downcast=None)

将参数转换为数字类型。
默认返回dtype为float64或int64, 具体取决于提供的数据。使用downcast参数获取其他dtype。

  • arg:scalar, list, tuple, 1-d array, or Series
  • errors:
    • ignore:只对数字字符串转换,其他类型一律不转换,包含时间类型
    • raise:遇到非数字字符串类型报错,bool类型报错,时间类型转换为int
    • coerce:将时间字符串和bool类型转换为数字,其他均转换为NaN
  • downcast:{‘integer’, ‘signed’, ‘unsigned’, ‘float’ }指定转换的类型,默认返回float64或int64
In:	import pandas as pd
	df = pd.Series(['1','2','4.7','pandas','10'])
	df
	
Out:	0         1
		1         2
		2       4.7
		3    pandas
		4        10
		dtype: object
In: pd.to_numeric(df,errors='coerce')
Out: 	0     1.0
		1     2.0
		2     4.7
		3     NaN
		4    10.0
		dtype: float64

3.带特殊符号的数据类型转换(自定义转化)

20162017
0$125,000.00$162500.00
1$920,000.00$101,2000.00
2$50,000.00$62500.00
3$350,000.00$490000.00
4$15,000.00$12750.00

将此数据改为浮点数

In: def convert_money(value):
    	new_value = value.replace("$","").replace(",","")
    	return float(new_value)


	df['2016'].apply(convert_money)
Out:
		0    125000.0
		1    920000.0
		2     50000.0
		3    350000.0
		4     15000.0
		Name: 2016, dtype: float64

Percent Growth
030.00%
1
210.00%
325.00%
44.00%
5-15.00%

将此数据改为浮点数

In: df['Percent Growth'].apply(lambda x: float(x.replace("%", "")) / 100)
Out:
	0    0.30
	1    0.10
	2    0.25
	3    0.04
	4   -0.15
	Name: Percent Growth, dtype: float64

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值