pandas 处理数据的一点经验

pandas 是 Python 中一个非常强大的数据处理包,几乎所有的数据预处理都可以通过它来完成。

pandas 中有两种类型的数据结构,分别是 DataFrame 和 Series。Series是一个一维的类似的数组对象,包含一个数组的数据(任何NumPy的数据类型)和一个与数组关联的数据标签,被叫做 索引 。Series 有点类似于字典,它的每一个索引(index)唯一对应着一个值(value)

1
2
3
4
5
6
7
8
9
10
11
12
13
# 创建 Series 数据
In [4]: obj = Series([4, 7, -5, 3])
In [5]: obj
Out[5]:
0 4
1 7
2 -5
3 3
# 值和索引
In [6]: obj.values
Out[6]: array([ 4, 7, -5, 3])
In [7]: obj.index
Out[7]: Int64Index([0, 1, 2, 3])

DataFrame 表示一个表格,类似电子表格的数据结构,包含一个经过排序的列表集,它们每一个都可以有不同的类型值(数字,字符串,布尔等等)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
'year': [2000, 2001, 2002, 2001, 2002],
'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}
frame = DataFrame(data)
```

![](http://raw.githubusercontent.com/swordspoet/i/img/778d5ca9ly1fh6quml61ij23v92ky1l2.jpg)

# 一、显示全部的列名 #

DataFrame 中包含了许多列,pandas 会用省略号来代替显示全部的行和列,可以通过一个小技巧来显示

```python
DataFrame.columns.tolist()

二、连接 MySQL

连接 MySQL 的前提是 MySQL 已经安装,并且 Python 中也安装了 MySQLdb 包,满足两个条件之后,便可以通过编写好的 sql 语句直接从数据库中读取数据了,并且读取的数据还可以保存为 DataFrame 格式。

1
2
3
4
db_conn = MySQLdb.connect('localhost', 'root', '312624', 'baoliao', charset="utf8")
# 截取从2017-02-01至2017-04-12年之间的用户爆料的单品数据
sql = "select * from sampleDB where baoliao_sampleDB_for_model where baoliao_time>='2017-02-01' and baoliao_time<'2017-04-12'"
sample = pd.read_sql(sql02, db_conn,) and is_shangjia_baoliao='用户爆料' and is_danpin='单品'"

三、统计各列下缺失值数

1
DataFrame.isnull().sum()

四、统计各列下每个值的频数

1
DataFrame.value_counts()

五、四舍五入

1
round(value, decimals)

对某个特征值下的全部数据进行四舍五入操作,

1
data[''] = [round(value, 2) for value in data['']]

六、排序

1
2
# 对单列数据进行升序排序
DataFrame.sort([""], ascending=True)

七、处理非连续值

非连续值可以将取值进行唯一编码

1
2
3
4
5
6
cat = pd.Categorical(["1", "2", "c", "d"]).codes
cat
Out[19]: array([0, 1, 2, 3], dtype=int8)
cat = pd.Categorical(["1", "2", "c", "c"]).codes
cat
Out[21]: array([0, 1, 2, 2], dtype=int8)

八、处理缺失值

pandas.to_numeric(arg, errors=’raise’, downcast=None)

errors 的参数设置有三种情形:

  • 如果是 ‘raise’,无效的数据将以例外的形式提示
  • 如果是 ‘coerce’,无效的数据将设置为 NaN
  • 如果是 ‘ignore’,无效的解析会被 pandas 直接忽略并返回到输入中

downcast 的参数设置也有三种情形:

  • ‘integer’ or ‘signed’: smallest signed int dtype (min.: np.int8)
  • ‘unsigned’: smallest unsigned int dtype (min.: np.uint8)
  • ‘float’: smallest float dtype (min.: np.float32)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
>>> import pandas as pd
>>> s = pd.Series(['1.0', '2', -3])
>>> pd.to_numeric(s)
0 1.0
1 2.0
2 -3.0
dtype: float64
>>> pd.to_numeric(s, downcast='float')
0 1.0
1 2.0
2 -3.0
dtype: float32
>>> pd.to_numeric(s, downcast='signed')
0 1
1 2
2 -3
dtype: int8
>>> s = pd.Series(['apple', '1.0', '2', -3])
>>> pd.to_numeric(s, errors='ignore')
0 apple
1 1.0
2 2
3 -3
dtype: object
>>> pd.to_numeric(s, errors='coerce')
0 NaN
1 1.0
2 2.0
3 -3.0
dtype: float64

对列中的缺失数据值填充

1
2
# 零值填充
DataFrame.fillna(0, inplace=True)

九、转换数据类型

在 pandas 中将 object 类型数据转换成 float 型,通过convert_objects(convert_numeric=True)便可实现,参考链接:stackoverflow: Convert pandas.Series from dtype object to float, and errors to nans

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
In [2]: a = pd.Series([1,2,3,4,'.'])

In [3]: a
Out[3]:
0 1
1 2
2 3
3 4
4 .
dtype: object

In [30]: pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
Out[30]:
0 1
1 2
2 3
3 4
4 NaN
dtype: float64

十、列的操作:增删改

1
2
3
4
5
6
7
8
9
10
# 插入列
df.insert(idx, col_name, value)
# 删除某列
del data['']
df.drop(['col_name'], axis=1)
# 删除某行
df.drop(['row_name'], axis=0)
# 修改列名
df.columns = ['', '', '']
df.rename(columns={'a': A', 'b': 'B'})

十一、去重复值

1
df.drop_duplicates(['col_name'])

参考链接

  1. oreilly: 处理缺失数据
  2. Python for Data Analysis: pandas入门
------本文结束,欢迎收藏本站、分享、评论或联系作者!------
点击查看
赠人玫瑰 手有余香
0%