pandas 数据类型研究(一)数据转换
当利用pandas进行数据处理的时候,经常会遇到数据类型的问题,当拿到数据的时候,首先需要确定拿到的是正确类型的数据,一般通过数据类型的转化,这篇文章就介绍pandas里面的数据类型(data types也就是常用的dtyps),以及pandas与numpy之间的数据对应关系。

dataframe中的 object 类型来自于 Numpy, 他描述了每一个元素 在 ndarray 中的类型 (也就是Object类型)。而每一个元素在 ndarray 中 必须用同样大小的字节长度。 比如 int64 float64, 他们的长度都是固定的 8 字节。
但是对于string 来说,string 的长度是不固定的, 所以pandas 储存string时 使用 narray, 每一个object 是一个指针
我们以官网案例作为解析,这样可以省去很多时间。
import pandas as pd
import numpy as np df = pd.read_csv("https://github.com/chris1610/pbpython/blob/master/data/sales_data_types.csv?raw=True")

然后我们查看每个字段的数据类型:

数据类型问题如下:
Customer number 应该是int64,不应该是float64
2016和2017两个字段是object字符串,但我们应该将其转换为float64或者int64
Percent Growth 应该是数字,但是这里是object字符串
Year、Month、Day 三个字段应该合并为一个datetime类型的日期数据
Active应该是bool型数据
数据类型转换的方法
转换数据类型的思路
使用astype()方法强制转化dtype
自定义一个数据转换函数函数
使用pandas内置的tonumeric()和todatetime()
导入数据时转换数据类型
1、使用astype()方法
处理pandas数据类型最简单的办法是astype()
df['Customer Number'].astype('int')

def astype(self, dtype, copy=True, errors='raise', **kwargs):
##############################################################
dtype : data type, or dict of column name -> data type
Use a numpy.dtype or Python type to cast entire pandas object to
the same type. Alternatively, use {col: dtype, ...}, where col is a
column label and dtype is a numpy.dtype or Python type to cast one
or more of the DataFrame's columns to column-specific types.
errors : {'raise', 'ignore'}, default 'raise'.
Control raising of exceptions on invalid data for provided dtype. - ``raise`` : allow exceptions to be raised
- ``ignore`` : suppress exceptions. On error return original object raise_on_error : DEPRECATED use ``errors`` instead
kwargs : keyword arguments to pass on to the constructor
##############################################################
方法:
df["Customer Number"] = df['Customer Number'].astype('int')
df=df.astype({"Customer Number":'int64'})
df.dtypes

那么如何将2016、2017、PercentGrowth、JanUnits列 从 字符串 转化为 数字,很明显传统的astype的方法是不行的。
需要自定义类型转换方法。
2、自定义转换函数
自定义:
以 2016和2017列为例,在强制从字符串转为数字之前,我们需要先将 "$"、"."、"," 剔除掉,然后再转换。
def convert_currency(val):
"""
Convert the string number value to a float
- Remove $
- Remove commas
- Convert to float type
"""
new_val = val.replace(',','').replace('$', '')
return float(new_val)
df['']=df[''].apply(convert_currency)
df.dtypes

也可以使用lamda表达式
例如下面的
df['Percent Growth']=df['Percent Growth'].apply(lambda x: x.replace('%', '')).astype('float') / 100
df.dtypes

np.where()方法:
np.where(condition, do1, do2)
如果condition满足条件,执行do1,否则执行do2
import numpy as np
df["Active"] = np.where(df["Active"] == "Y", True, False)
df

3、pandas内置的处理函数
pandas还有
pd.to_numeric(arg,errors='raise')
pd.to_datetime(arg,errors='raise')
函数帮助我们转为数据类型。
errors参数有:
raise, errors默认为raise
ignore 忽略错误,并把转化前的值直接返回
coerce 将错误数据标注为NaN
因为数据不一定是干净的,对于错误数据我们有三种处理措施。
pd.to_numeric(df['Jan Units'], errors='coerce')

pd.to_numeric(df['Jan Units'], errors='ignore')

to_datetime
convert the separate month, day and year columns into a datetime . The pandas pd.to_datetime() function is quite configurable but also pretty smart by default.
he function combines the columns into a new series of the appropriate datateime64 dtype.
df["Start_Date"] = pd.to_datetime(df[['Month', 'Day', 'Year']])

四、导入数据时转换数据类型
除了上面的三种方法,实际上我们也可以在导入数据的时候就处理好。
def convert_currency(val):
"""
Convert the string number value to a float
- Remove $
- Remove commas
- Convert to float type
"""
new_val = val.replace(',','').replace('$', '')
return float(new_val) df_2 = pd.read_csv("https://github.com/chris1610/pbpython/blob/master/data/sales_data_types.csv?raw=True",
dtype={'Customer Number': 'int'},
converters={'': convert_currency,
'': convert_currency,
'Percent Growth': lambda x: float(x.replace('%', '')) / 100,
'Jan Units': lambda x: pd.to_numeric(x, errors='coerce'),
'Active': lambda x: np.where(x == "Y", True, False)
})

这章内容参考博客见文档
pandas 数据类型研究(一)数据转换的更多相关文章
- pandas数据类型(二)与numpy的str和object类型之间的区别
		
现象: Numpy区分了str和object类型,其中dtype(‘S’)和dtype(‘O’)分别对应于str和object. 然而,pandas缺乏这种区别 str和object类型都对应dtyp ...
 - Excel种的数据类型研究【原创】【精】
		
因为要做一个项目,开始研究Excel种的数据类型.发现偌大的一个cnblogs竟然没人写这个,自己研究以后记录下来. 在我们通常的认识中,Excel中的数据类型有这么几种 1.常规:2.数值:3.货币 ...
 - Python数据分析与展示[第三周](pandas数据类型操作)
		
数据类型操作 如何改变Series/ DataFrame 对象 增加或重排:重新索引 删除:drop 重新索引 .reindex() reindex() 能够改变或重排Series和DataFrame ...
 - Javascript判断object还是list/array的类型(包含javascript的数据类型研究)
		
前提:先研究javascript中的变量有几种,参考: http://www.w3school.com.cn/js/js_datatypes.asp http://glzaction.iteye.co ...
 - pandas(九)数据转换
		
移除重复数据 dataframe中常常会出现重复行,DataFrame对象的duplicated方法返回一个布尔型的Series对象,可以表示各行是否是重复行.还有一个drop_duplicates方 ...
 - pandas数据类型判断(三)数据判断
		
1.函数:空值判断 1)判断数值是否为空用 pd.isna,pd.isnull,np.isnan2)判断字符串是否为空用 pd.isna,pd.isnull:3)判断时间是否为空用 pd.isna,p ...
 - AnsiString和各种数据类型间相互转换 [数据转换]
		
//Ansistring 转 char void __fastcall TForm1::Button1Click(TObject *Sender) { AnsiString Test = " ...
 - float数据类型研究,发现其能显示的有效数字极为有限
		
1. 范围 float和double的范围是由指数的位数来决定的. float的指数位有8位,而double的指数位有11位,分布如下: float: 1bit(符号位) 8bits(指数位) ...
 - pandas 实现rfm模型
		
import pandas as pd import numpy as np df = pd.read_csv('./zue_164466.csv') df['ptdate'] = pd.to_dat ...
 
随机推荐
- SpringCloud服务注册与发现中心-Eureka
			
1.服务注册与发现的好处: 假设没有这个东西,那么如果存在a,b,c三个同样的服务: 而现在有一个u服务需要用到a或b或c提供的接口,那么u里面肯定是需要配置这三个服务的地址,然后调用的时候还有问题就 ...
 - 【转帖】K8S Deployment 命令
			
K8S Deployment 命令 https://www.cnblogs.com/Tempted/p/7831604.html 今天学习了一下 kubectl scale deployment xx ...
 - yzoj 2377 颂芬梭哈 题解
			
题意 Alice 和 Mukyu 最近偶然得到了一本写有一种叫做梭哈的扑克游戏的规则的说明书(名为<C████████nd>,中间部分被涂掉了),据其所述,梭哈是一种使用黑桃.红心.梅花. ...
 - oracle如何保证数据一致性和避免脏读
			
oracle通过undo保证一致性读和不发生脏读 1.不发生脏读2.一致性读3. 事务槽(ITL)小解 1.不发生脏读 例如:用户A对表更新了,没有提交,用户B对进行查询,没有提交的更新不能出现在 ...
 - 初始NLTK
			
NLTK官网:链接 Natural Language Toolkit NLTK corpora and lexical resources such as WordNet, along with a ...
 - 微信公众号h5页面自定义分享
			
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...
 - PB笔记之调用数据窗口时的过滤条件添加方式
			
在PB查询数据窗口的数据时 通常可以有两种方式 一是在数据窗口事先写好查询条件,然后用retrieve()函数通过参数传递给数据窗口 这种方式适合查询条件较为简单,条件数较少的数据窗口 二是使用Set ...
 - websocket 协议简述
			
WebSocket 是一种网络通信协议,RFC 6455 定义了它的通信标准,属于服务器推送技术的一种 由于 HTTP 无状态.无连接.单向通信的特性,导致 HTTP 协议无法实现服务器主动向客户端发 ...
 - JDK8源码解析 -- HashMap(一)
			
最近一直在忙于项目开发的事情,没有时间去学习一些新知识,但用忙里偷闲的时间把jdk8的hashMap源码看完了,也做了详细的笔记,我会把一些重要知识点分享给大家.大家都知道,HashMap类型也是面试 ...
 - 第4章 JIT编译器
			
4.1 JIT概览 语言根据执行的方式不同分为编译型语言和解释型语言.以C++为代表的编译型语言在执行前需要编译成机器码,不同的CPU需要不同的编译器,编译成功后在同一台机器不需再次编译.以Pytho ...