Pandas 数据类型概述与转换实战
The following article is from 萝卜大杂烩 Author 周萝卜
Pandas 数据类型
数据类型本质上是编程语言用来理解如何存储和操作数据的内部结构。例如,一个程序需要理解将两个数字相加,如 5 + 10 得到 15。或者有两个字符串,如“cat”和“hat”,可以将它们连接(加)在一起得到“cathat”
关于 pandas 数据类型的一个可能令人困惑的地方是 pandas、python 和 numpy 之间存在一些出入
下表做了相关的总结
Pandas dtype
Python type
NumPy type
Usage
object | str or mixed | string_, unicode_, mixed types | Text or mixed numeric and non-numeric values |
int64 | int | int_, int8, int16, int32, int64, uint8, uint16, uint32, uint64 | Integer numbers |
float64 | float | float_, float16, float32, float64 | Floating point numbers |
bool | bool | bool_ | True/False values |
datetime64 | NA | datetime64[ns] | Date and time values |
timedelta[ns] | NA | NA | Differences between two datetimes |
category | NA | NA | Finite list of text values |
不过在大多数情况下,无需担心是否应该尝试显式地将 pandas 类型强制为对应于 NumPy 类型。大多数时候,使用 pandas 默认的 int64 和 float64 类型就可以了
下面我们将重点介绍以下 pandas 类型:
object int64 float64 datetime64 bool
而对于category 和 timedelta 类型,我们会在后面的文章中重点介绍
还需要注意的是object
数据类型实际上可以包含多种不同的类型。例如,a 列可以包括整数、浮点数和字符串,它们统称为object
。因此,我们可能需要一些额外的技术来处理object
列中的混合数据类型,我们也在后面的文章专门讨论
下面我们先来查看本文使用的测试数据
import numpy as np
import pandas as pd
df = pd.read_csv("sales_data_types.csv")
Output:
乍一看数据好像还不错,所以我们可以尝试做一些操作来分析数据。让我们尝试将 2016 年和 2017 年的销售额相加:
df['2016'] + df['2017']
Output:
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
dtype: object
结果显然不是我们期望的,我们希望将总数加在一起,但 pandas 只是将两个值连接在一起。其实问题也很明显,我们的数据类型是dtype: object
,object 是 pandas 中的字符串,因此它执行字符串操作而不是数学操作
我们可以通过如下代码查看数据所有的数据类型信息
df.dtypes
Output:
Customer Number float64
Customer Name object
2016 object
2017 object
Percent Growth object
Jan Units object
Month int64
Day int64
Year int64
Active object
dtype: object
当然我们还可以使用df.info()
来查看更多信息
df.info()
Output:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 10 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Customer Number 5 non-null float64
1 Customer Name 5 non-null object
2 2016 5 non-null object
3 2017 5 non-null object
4 Percent Growth 5 non-null object
5 Jan Units 5 non-null object
6 Month 5 non-null int64
7 Day 5 non-null int64
8 Year 5 non-null int64
9 Active 5 non-null object
dtypes: float64(1), int64(3), object(6)
memory usage: 528.0+ bytes
Customer Number 是 float64 但应该是 int64
2016 和 2017 列存储为 object,而不是诸如 float64 或 int64 之类的数值
百分比增长和 Month 单位也存储为 object 而不是数值
列 Month 、 Day 和 Year 应转换为 datetime64 类型
Active 列应该是一个布尔值
使用 astype() 强制转换数据类型
创建自定义函数来转换数据
使用 pandas 函数,例如 to_numeric() 或 to_datetime()
使用 astype() 函数
将 pandas 数据列转换为不同类型的最简单方法是使用 astype(),例如,要将 Customer Number 转换为整数,我们可以这样调用它:
df['Customer Number'].astype('int')
Output:
0 10002
1 552278
2 23477
3 24900
4 651029
Name: Customer Number, dtype: int32
df["Customer Number"] = df['Customer Number'].astype('int')
df.dtypes
Output:
Customer Number int32
Customer Name object
2016 object
2017 object
Percent Growth object
Jan Units object
Month int64
Day int64
Year int64
Active object
dtype: object
df['Active'].astype('bool')
1 True
2 True
3 True
4 True
Name: Active, dtype: bool
数据是干净的,可以简单地转换为一个数字
将数值转换为字符串对象
自定义转换函数
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)
1 920000.0
2 50000.0
3 350000.0
4 15000.0
Name: 2016, dtype: float64
df['2016'].apply(lambda x: x.replace('$', '').replace(',', '')).astype('float')
Customer Number int32
Customer Name object
2016 object
2017 object
Percent Growth object
Jan Units object
Month int64
Day int64
Year int64
Active bool
dtype: object
Pandas 辅助函数
pd.to_numeric(df['Jan Units'], errors='coerce')
1 700.0
2 125.0
3 75.0
4 NaN
Name: Jan Units, dtype: float64
pd.to_numeric(df['Jan Units'], errors='coerce').fillna(0)
1 700.0
2 125.0
3 75.0
4 0.0
Name: Jan Units, dtype: float64
1 2014-06-15
2 2016-03-29
3 2015-10-27
4 2014-02-02
dtype: datetime64[ns]
dtype={'Customer Number': 'int'},
converters={'2016': convert_currency,
'2017': convert_currency,
'Percent Growth': convert_percent,
'Jan Units': lambda x: pd.to_numeric(x, errors='coerce'),
'Active': lambda x: np.where(x == "Y", True, False)
})
df_2.dtypes
Customer Number int32
Customer Name object
2016 float64
2017 float64
Percent Growth float64
Jan Units float64
Month int64
Day int64
Year int64
Active object
dtype: object
技术资讯
分享
点收藏
点点赞
点在看