Python 数据处理技巧

本篇笔记记录使用 Python 进行数据处理的相关技巧:

  • Pandas 缺失数据处理
  • 数据类型转换

1. Pandas 处理缺失数据

Pandas 常用的处理缺失数据处理为特定数据值、特定字段指定数据值填充。当处理到两个表数据更新缺失值时,就需要使用其他方法。

1.1 combine_first 填充

不同数据源中均有一些缺失值,那么如何让他们相互“弥补”这些缺失值呢?可以考虑使用 combine_first

1
2
3
4
5
6
7
8
In [43]: df1 = pd.DataFrame([[np.nan, 3., 5.], [-4.6, np.nan, np.nan],
.....: [np.nan, 7., np.nan]])
.....:

In [44]: df2 = pd.DataFrame([[-42.6, np.nan, -8.2], [-5., 1.6, 4]],
.....: index=[1, 2])
.....:
In [45]: result = df1.combine_first(df2)

_images/merging_combine_first.png
例如上图中根据行列对应的值,df2 的值填充到得了 df1 缺失部分。

1.2 update 更新

上述方法仅仅填充了缺失值,如果需要把所有的值进行更新替换,可以考虑使用 update,这次替换的不仅仅是NaN值,还有其他所有能在右表中找到的相同位置的值。

1
In [46]: df1.update(df2)

_images/merging_update.png

2. 数据类型

Pandas 读取数据之后不一定能够符合需要或者数据字典说明,因此需要通过相应的方法将数据类型进行转化。

2.1 astype 转换

Pandas 可以使用 astype 进行强制类型转换,转换需要具有几个常用条件:1)数据整洁性,这样可以容易被转换;2)数值类型转换字符串类型比较容易。但是需要注意 ValueError 报错类型:

1
2
3
4
# 报错:因为对于某些字符串类型或者逗号分隔无法顺利进行数值类型转换
ValueError: could not convert string to float: '$15,000.00'

ValueError: invalid literal for int() with base 10: 'Closed'

这个是说强之类型转换失败,上面两个错误:第一个是因为第一个有逗号及单位符号;第二个错误是因为 cloed 是字符串。

⚠️另外需要注意的是,当使用 astype('bool') 转换为逻辑类型的时候,非空字符串都会被转换为 True

2.2 apply 调用函数

该方法比较 elegent,因为它解决了 astype 对数据不整洁的转化报错的问题。其 核心逻辑 是利用利用函数(同样可以使用 lambda 匿名函数来解决问题)将数据直接解析转换为另一个数据类型。

1
2
3
4
5
6
7
8
9
10
11
12
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)

# 使用 apply 方法调用函数
df['2016'].apply(convert_currency)

2.3 读取数据参数使用

在明确某些字段是什么类型的情况下,可以在读取阶段通过参数调整。核心逻辑pandasread 方法中的 converters 参数,下面是 read_csv 示例

1
2
3
4
5
6
7
# convert_currency 是一个函数
df = pd.read_csv("sales_data_types.csv",
dtype={'Customer Number': 'int'},
converters={'2016': convert_currency,
'Jan Units': lambda x: pd.to_numeric(x, errors='coerce'),
'Active': lambda x: np.where(x == "Y", True, False)
})

2.4 特定功能性接口

功能性方法是 pandas 自带方法,它们可以针对某些类型的数据进行转换,例如:pd.to_datetime()pd.to_numerical

作者

ZenRay

发布于

2019-04-10

更新于

2021-04-11

许可协议

CC BY-NC-SA 4.0