序
Excel是数据分钟中最常用的工具,通过Python和Excel功能对比,介绍如何使用Python通过函数式编程完成Excel中的数据处理及分析工作。
在Python中pandas库用于数据处理,我们从1787页的pandas官网文档中总结出最常用的36个函数,通过这些函数介绍如何通过Python完成数据生成和导入,数据清洗,预处理,以及最常见的数据分类,数据筛选,分类汇总,透视等最常见的操作。
第1章生成数据表
Excel
常见的生成数据表的方法有两种,第一种是导入外部数据,第二种是直接写入数据。
Excel中的“文件”菜单中提供了获取外部数据的功能,支持数据库和文本文件和页面的多种数据源导入。
Python
Python支持从多种类型的数据导入。
在开始使用Python进行数据导入之前需要先导入pandas库,为了方便起见,我们也同时导入numpy库
1.导入数据表
下面分别是Excel和csv格式文件中导入数据并创建数据表的方法。
代码是最简模式,里面有很多可选参数设置,例如列名称,索引列,数据格式。
help(pd.read_csv)
Help on function read_csv in module pandas.io.parsers:
read_csv(filepath_or_buffer, sep=',', delimiter=None, header='infer', names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, iterator=False, chunksize=None, compression='infer', thousands=None, decimal=b'.', lineterminator=None, quotechar='"', quoting=0, escapechar=None, comment=None, encoding=None, dialect=None, tupleize_cols=False, error_bad_lines=True, warn_bad_lines=True, skipfooter=0, skip_footer=0, doublequote=True, delim_whitespace=False, as_recarray=False, compact_ints=False, use_unsigned=False, low_memory=True, buffer_lines=None, memory_map=False, float_precision=None)
Read CSV (comma-separated) file into DataFrame
Also supports optionally iterating or breaking of the file
into chunks.
Additional help can be found in the `online docs for IO Tools
<http://pandas.pydata.org/pandas-docs/stable/io.html>`_.
Parameters
----------
filepath_or_buffer : str, pathlib.Path, py._path.local.LocalPath or any object with a read() method (such as a file handle or StringIO)
The string could be a URL. Valid URL schemes include http, ftp, s3, and
file. For file URLs, a host is expected. For instance, a local file could
be file ://localhost/path/to/table.csv
sep : str, default ','
Delimiter to use. If sep is None, will try to automatically determine
this. Separators longer than 1 character and different from ``'\s+'`` will
be interpreted as regular expressions, will force use of the python parsing
engine and will ignore quotes in the data. Regex example: ``'\r\t'``
delimiter : str, default ``None``
Alternative argument name for sep.
delim_whitespace : boolean, default False
Specifies whether or not whitespace (e.g. ``' '`` or ``' '``) will be
used as the sep. Equivalent to setting ``sep='\s+'``. If this option
is set to True, nothing should be passed in for the ``delimiter``
parameter.
.. versionadded:: 0.18.1 support for the Python parser.
header : int or list of ints, default 'infer'
Row number(s) to use as the column names, and the start of the data.
Default behavior is as if set to 0 if no ``names`` passed, otherwise
``None``. Explicitly pass ``header=0`` to be able to replace existing
names. The header can be a list of integers that specify row locations for
a multi-index on the columns e.g. [0,1,3]. Intervening rows that are not
specified will be skipped (e.g. 2 in this example is skipped). Note that
this parameter ignores commented lines and empty lines if
``skip_blank_lines=True``, so header=0 denotes the first line of data
rather than the first line of the file.
names : array-like, default None
List of column names to use. If file contains no header row, then you
should explicitly pass header=None. Duplicates in this list are not
allowed unless mangle_dupe_cols=True, which is the default.
index_col : int or sequence or False, default None
Column to use as the row labels of the DataFrame. If a sequence is given, a
MultiIndex is used. If you have a malformed file with delimiters at the end
of each line, you might consider index_col=False to force pandas to _not_
use the first column as the index (row names)
usecols : array-like, default None
Return a subset of the columns. All elements in this array must either
be positional (i.e. integer indices into the document columns) or strings
that correspond to column names provided either by the user in `names` or
inferred from the document header row(s). For example, a valid `usecols`
parameter would be [0, 1, 2] or ['foo', 'bar', 'baz']. Using this parameter
results in much faster parsing time and lower memory usage.
as_recarray : boolean, default False
DEPRECATED: this argument will be removed in a future version. Please call
`pd.read_csv(...).to_records()` instead.
Return a NumPy recarray instead of a DataFrame after parsing the data.
If set to True, this option takes precedence over the `squeeze` parameter.
In addition, as row indices are not available in such a format, the
`index_col` parameter will be ignored.
squeeze : boolean, default False
If the parsed data only contains one column then return a Series
prefix : str, default None
Prefix to add to column numbers when no header, e.g. 'X' for X0, X1, ...
mangle_dupe_cols : boolean, default True
Duplicate columns will be specified as 'X.0'...'X.N', rather than
'X'...'X'. Passing in False will cause data to be overwritten if there
are duplicate names in the columns.
dtype : Type name or dict of column -> type, default None
Data type for data or columns. E.g. {'a': np.float64, 'b': np.int32}
(Unsupported with engine='python'). Use `str` or `object` to preserve and
not interpret dtype.
engine : {'c', 'python'}, optional
Parser engine to use. The C engine is faster while the python engine is
currently more feature-complete.
converters : dict, default None
Dict of functions for converting values in certain columns. Keys can either
be integers or column labels
true_values : list, default None
Values to consider as True
false_values : list, default None
Values to consider as False
skipinitialspace : boolean, default False
Skip spaces after delimiter.
skiprows : list-like or integer, default None
Line numbers to skip (0-indexed) or number of lines to skip (int)
at the start of the file
skipfooter : int, default 0
Number of lines at bottom of file to skip (Unsupported with engine='c')
skip_footer : int, default 0
DEPRECATED: use the `skipfooter` parameter instead, as they are identical
nrows : int, default None
Number of rows of file to read. Useful for reading pieces of large files
na_values : scalar, str, list-like, or dict, default None
Additional strings to recognize as NA/NaN. If dict passed, specific
per-column NA values. By default the following values are interpreted as
NaN: '', '#N/A', '#N/A N/A', '#NA', '-1.#IND', '-1.#QNAN', '-NaN', '-nan',
'1.#IND', '1.#QNAN', 'N/A', 'NA', 'NULL', 'NaN', 'nan'`.
keep_default_na : bool, default True
If na_values are specified and keep_default_na is False the default NaN
values are overridden, otherwise they're appended to.
na_filter : boolean, default True
Detect missing value markers (empty strings and the value of na_values). In
data without any NAs, passing na_filter=False can improve the performance
of reading a large file
verbose : boolean, default False
Indicate number of NA values placed in non-numeric columns
skip_blank_lines : boolean, default True
If True, skip over blank lines rather than interpreting as NaN values
parse_dates : boolean or list of ints or names or list of lists or dict, default False
* boolean. If True -> try parsing the index.
* list of ints or names. e.g. If [1, 2, 3] -> try parsing columns 1, 2, 3
each as a separate date column.
* list of lists. e.g. If [[1, 3]] -> combine columns 1 and 3 and parse as
a single date column.
* dict, e.g. {'foo' : [1, 3]} -> parse columns 1, 3 as date and call result
'foo'
Note: A fast-path exists for iso8601-formatted dates.
infer_datetime_format : boolean, default False
If True and parse_dates is enabled, pandas will attempt to infer the format
of the datetime strings in the columns, and if it can be inferred, switch
to a faster method of parsing them. In some cases this can increase the
parsing speed by ~5-10x.
keep_date_col : boolean, default False
If True and parse_dates specifies combining multiple columns then
keep the original columns.
date_parser : function, default None
Function to use for converting a sequence of string columns to an array of
datetime instances. The default uses ``dateutil.parser.parser`` to do the
conversion. Pandas will try to call date_parser in three different ways,
advancing to the next if an exception occurs: 1) Pass one or more arrays
(as defined by parse_dates) as arguments; 2) concatenate (row-wise) the
string values from the columns defined by parse_dates into a single array
and pass that; and 3) call date_parser once for each row using one or more
strings (corresponding to the columns defined by parse_dates) as arguments.
dayfirst : boolean, default False
DD/MM format dates, international and European format
iterator : boolean, default False
Return TextFileReader object for iteration or getting chunks with
``get_chunk()``.
chunksize : int, default None
Return TextFileReader object for iteration. `See IO Tools docs for more
information
<http://pandas.pydata.org/pandas-docs/stable/io.html#io-chunking>`_ on
``iterator`` and ``chunksize``.
compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'
For on-the-fly decompression of on-disk data. If 'infer', then use gzip,
bz2, zip or xz if filepath_or_buffer is a string ending in '.gz', '.bz2',
'.zip', or 'xz', respectively, and no decompression otherwise. If using
'zip', the ZIP file must contain only one data file to be read in.
Set to None for no decompression.
.. versionadded:: 0.18.1 support for 'zip' and 'xz' compression.
thousands : str, default None
Thousands separator
decimal : str, default '.'
Character to recognize as decimal point (e.g. use ',' for European data).
float_precision : string, default None
Specifies which converter the C engine should use for floating-point
values. The options are `None` for the ordinary converter,
`high` for the high-precision converter, and `round_trip` for the
round-trip converter.
lineterminator : str (length 1), default None
Character to break file into lines. Only valid with C parser.
quotechar : str (length 1), optional
The character used to denote the start and end of a quoted item. Quoted
items can include the delimiter and it will be ignored.
quoting : int or csv.QUOTE_* instance, default 0
Control field quoting behavior per ``csv.QUOTE_*`` constants. Use one of
QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3).
doublequote : boolean, default ``True``
When quotechar is specified and quoting is not ``QUOTE_NONE``, indicate
whether or not to interpret two consecutive quotechar elements INSIDE a
field as a single ``quotechar`` element.
escapechar : str (length 1), default None
One-character string used to escape delimiter when quoting is QUOTE_NONE.
comment : str, default None
Indicates remainder of line should not be parsed. If found at the beginning
of a line, the line will be ignored altogether. This parameter must be a
single character. Like empty lines (as long as ``skip_blank_lines=True``),
fully commented lines are ignored by the parameter `header` but not by
`skiprows`. For example, if comment='#', parsing '#empty\na,b,c\n1,2,3'
with `header=0` will result in 'a,b,c' being
treated as the header.
encoding : str, default None
Encoding to use for UTF when reading/writing (ex. 'utf-8'). `List of Python
standard encodings
<https://docs.python.org/3/library/codecs.html#standard-encodings>`_
dialect : str or csv.Dialect instance, default None
If None defaults to Excel dialect. Ignored if sep longer than 1 char
See csv.Dialect documentation for more details
tupleize_cols : boolean, default False
Leave a list of tuples on columns as is (default is to convert to
a Multi Index on the columns)
error_bad_lines : boolean, default True
Lines with too many fields (e.g. a csv line with too many commas) will by
default cause an exception to be raised, and no DataFrame will be returned.
If False, then these "bad lines" will dropped from the DataFrame that is
returned. (Only valid with C parser)
warn_bad_lines : boolean, default True
If error_bad_lines is False, and warn_bad_lines is True, a warning for each
"bad line" will be output. (Only valid with C parser).
low_memory : boolean, default True
Internally process the file in chunks, resulting in lower memory use
while parsing, but possibly mixed type inference. To ensure no mixed
types either set False, or specify the type with the `dtype` parameter.
Note that the entire file is read into a single DataFrame regardless,
use the `chunksize` or `iterator` parameter to return the data in chunks.
(Only valid with C parser)
buffer_lines : int, default None
DEPRECATED: this argument will be removed in a future version because its
value is not respected by the parser
compact_ints : boolean, default False
DEPRECATED: this argument will be removed in a future version
If compact_ints is True, then for any column that is of integer dtype,
the parser will attempt to cast it as the smallest integer dtype possible,
either signed or unsigned depending on the specification from the
`use_unsigned` parameter.
use_unsigned : boolean, default False
DEPRECATED: this argument will be removed in a future version
If integer columns are being compacted (i.e. `compact_ints=True`), specify
whether the column should be compacted to the smallest signed or unsigned
integer dtype.
memory_map : boolean, default False
If a filepath is provided for `filepath_or_buffer`, map the file object
directly onto memory and access the data directly from there. Using this
option can improve performance because there is no longer any I/O overhead.
Returns
-------
result : DataFrame or TextParser
2.创建数据表
另一种方法是通过直接写入数据来生成数据表,Excel中直接在单元格中输入数据就可以,Python中通过下面的代码来实现。
生成数据表的函数是pandas库中的DataFrame函数,数据表一共有6行数据,每行有6个字段。在数据中我们特意设置了一些NA值和有问题的字段,例如包含空格等。
后面将在数据清洗步骤进行处理。
后面我们将统一以DataFrame的简称df来命名数据表。
以上是刚刚创建的数据表,我们没有设置索引列,price字段中包含有NA值,city字段中还包含了一些脏数据。
第2章数据表检查
本章主要介绍对数据表进行检查。
Python中处理的数据量通常会比较大,比如纽约的出租车数据和Citibike的骑行数据,其数据量都在千万级,我们无法一目了然地了解数据表的整体情况,必须要通过一些方法来获得数据表的关键信息。
数据表检查的另一个目的是了解数据的概况,例如整个数据表的大小,所占空间,数据格式,是否有空值和具体的数据内容,为后面的清洗和预处理做好准备。
1.数据维度(行列)
Excel中可以通过CTRL+向下的光标键,和CTRL+向右的光标键来查看行号和列好。
Python中使用shape函数来产看数据表的维度,也就是行数和列数,函数返回的结果(6,6)表示数据表有6行,6列。
下面是具体的代码。
2.数据表信息
使用info函数查看数据表的整体信息,这里返回的信息比较多,包括数据维度、列名称、数据格式和所占空间等信息。
3.查看数据格式
Excel中通过选中单元格并查看开始菜单中的数值类型来判断数据的格式。
Python中使用dtypes函数来返回数据格式。
dtyps是一个查看数据格式的函数,可以一次性查看数据表中所有数据的格式,也可以指定一列来单独查看。
4.查看空值
Excel中查看空值的方法是使用‘定位条件’功能对数据表中的空值进行定位。
‘定位条件’在‘开始’目录下的‘查找和选择’目录中。
Isnull是Python中检验空值的函数,返回的结果是逻辑值,包含空值返回True,不包含则返回False。
用户既可以对整个数据表进行检查,也可以单独对某一列进行空值检查。
5.查看唯一值
Excel中查看唯一值得方法是使用‘条件格式’对唯一值进行颜色标记。
Python中是用unique函数查看唯一值。
Unique是查看唯一值的函数,只能对数据表中的特定列进行检查。
下面是代码,返回的结果是该列中的唯一值。
类似与Excel中删除重复项后的结果。
6.查看数据表数值
Python中的Values函数用来查看数据表中的数值。
以数组的形式返回,不包含表头信息。
7.查看列名称
8.查看前10行数据
Head()函数用来查看数据表中前N行数据,默认head()显示前10行数据,可以自己设置参数值来确定查看的行数。
下面的代码中设置查看前3行的数据。
9.查看后10行数据
tail函数与head函数相反,用来查看数据表中后N行的数据,默认tail()显示后10行数据,可以自己设置参数值来确定查看的行数。
下面的代码中设置查看后3行的数据。
第3章数据表清洗
本章介绍的是对数据表中的问题进行清洗,主要内容包括对空值、大小写问题、数据格式和重复值的处理。
这里不包含对数据间的逻辑验证。
1.处理空值(删除或填充)
我们在创建数据表的时候在price字段中故意设置了几个NA值。
对于空值的处理方式有很多种,可以直接删除包含空值的数据,也可以对控制进行填充,比如用0填充或者用均值填充。还可以根据不同字段的逻辑对空值进行推算。
Excel中可以通过‘查找和替换’功能对空值进行处理,将空值统一替换为0或均值。也可以通过‘定位’空值来实现。
Python中处理空值的方法比较灵活,可以使用Dropna函数用来删除数据表中包含空值的数据,也可以使用fillna函数对空值进行填充。下面的代码和结果中可以看到使用dropna函数后,包含NA值得两个字段已经不见了。返回的是一个不包含空值的数据表。
除此之外,也可以使用数字对空值进行填充,下面的代码使用fillna函数对空值字段填充数字0.
我们选择填充的方式来处理空值,使用price列的均值来填充NA字段,同样使用fillna函数,在要填充的数值中使用mean函数先计算price列当前的均值,然后使用这个均值对NA进行填充。可以看到两个空值字段显示为3299.5
2.清理空格
处理空值,字段中的空格也是数据清洗中一个常见的问题,下面是清楚字符中空格的代码。
3.大小写转换
在英文字段中,字母的大小写不统一也是一个常见的问题。
Excel中有UPPER,LOWER等函数,Python中也有同名函数用来解决大小写的问题。在数据表的city列中就存在这样的问题。
我们将city列的所有字母转换为小写。下面是具体的代码和结果。
4.更改数据格式
Excel中通过‘设置单元格格式’功能可以修改数据格式。
Python中通过astype函数用来修改数据格式。
Python中dtype是查看数据格式的函数,与之对应的是astype函数,用来更改数据格式。下面的代码将price字段的值修改为int格式。
5.更改列名称
Rename是更改列名称的函数,我们将来数据表中的category列更改为category-size。
下面是具体的代码和更改后的结果。
6.删除重复值
很多数据表中还包含重复值的问题,Excel的数据目录下有‘删除重复项’的功能,可以用来删除数据表中的重复值。
默认Excel会保留最先出现的数据,删除后面重复出现的数据。
Python中使用drop_duplicates函数删除重复值。
我们以数据表中的city列为例,city字段中存在重复值。
默认情况下drop_duplicates()将删除后出现的重复值(与Excel逻辑一致)。增加keep='last'参数后将删除最先出现的重复值,保留最后的值。
下面是具体的代码和比较结果。
使用默认的drop_duplicates()函数删除重复值,从结果中可以看到第一位的beijing被保留,最后出现的beijing被删除。
设置keep='last'参数后,与之前删除重复值的结果相反,第一位出现的beijing被删除,保留了最后一位出现的beijing。
7.数值修改及替换
数据清洗中最后一个问题是数值修改或替换,Excel中使用“查找和替换”功能就可以实现数值的替换。
Python中使用replace函数实现数据替换。
数据表中city字段上海存在两种写法,分别为shanghai和SH。
我们使用replace函数对SH进行替换。
第4章 数据预处理
本章主要讲的是数据的预处理,对清洗完的数据进行整理以便后期的统计和分析工作。
主要包括数据表的合并,排序,数值分列,数据分组及标记等工作。
1.数据表合并
首先是对不同的数据表进行合并,我们这里创建一个新的数据表df1,并将df和df1两个数据表进行合并。
在Excel中没有直接完成数据表合并的功能,可以通过vlookup函数分步实现。
在Python中可以通过merge函数一次性实现。
下面建立df1数据表,用于和df数据表进行合并。
使用merge函数对两个数据表进行合并,合并的方式为inner,将两个数据表中共有的数据匹配到一起生成新的数据表。并命名为df_inner。
除了inner方式以外,合并的方式还有left,right和outer方式。这几种方式的差别在我其他的文章中有详细的说明和对比。
2.设置索引列
完成数据表的合并后,我们对df_inner数据表设置索引列,索引列的功能很多,可以进行数据提取,汇总,也可以进行数据筛选等。
设置索引的函数为set_index.
3.排序(按索引,按数值)
Excel中可以通过数据目录下的排序按钮直接对数据表进行排序,比较简单。
Python中需要使用ort_values函数和sort_index函数完成排序。
在Python中,既可以按索引对数据表进行排序,也可以看置顶列的数值进行排序。
首先我们按age列中用户的年龄对数据表进行排序。
使用的函数为sort_values.
Sort_index函数用来将数据表按索引列的值进行排序。
4.数据分组
Excel中可以通过vlookup函数进行近似匹配来完成对数值的分组,或者使用“数据透视表”来完成分组。
相应的Python中使用where函数完成数据分组。
where函数用来对数据进行判断和分组,下面的代码中我们对price列的值进行判断,将符合条件的分为一组,不符合条件的分为另一组,并使用group字段进行标记。
除了where函数以外,还可以对多个字段的值进行判断后对数据进行分组,下面的代码中对city列等于beijing并且price列大于等于4000的数据标记为1.
5.数据分列
与数据分组相反的是对数值进行分列,Excel中的数据目录下提供‘分列’功能。
在Python中使用split函数实现分列。
在数据表中category列中的数据包含有两个信息,前面的数字为类别id,后面的字母为size值。中间以连字符进行联结。我们使用split函数对这个字段进行拆分,并将拆分后的数据表匹配回原数据表中。
第5章数据提取
数据提取,也就是数据分析中最常见的一个工作。
这部分主要使用3个函数,即loc,iloc和ix。
loc函数按标签值进行提取;
iloc函数按位置进行提取;
ix函数可以同时按标签和位置进行提取。
下面介绍每一种函数的使用方法。
1.按标签提取loc函数
loc函数按数据表的索引标签进行提取,下面的代码中提取了索引列为3的单条数据。
使用冒号可以限定提取数据的范围,冒号前面为开始的标签值,后面为结束的标签值。
下面提取了0-5的数据行。
Reset_index函数用于恢复索引,这里我们重新将date字段的日期设置为数据表的索引,并按日期进行数据提取。
使用冒号限定提取数据的范围,冒号前面为空表示从0开始。
提取所有2013年1月4日以前的数据。
2.按位置提取 iloc函数
使用iloc函数按位置对数据表中的数据进行提取,这里冒号前后的数字不再是索引的标签名称,而是数据所在的位置,从0开始。
iloc函数除了可以按区域提取数据,还可以按位置逐条提取,前面方括号中的0,2,5,表示数据所在行的位置,后面方括号中的数表示所在列的位置。
3.按标签和位置提取 ix函数
ix是loc和iloc的混合,既能按索引标签提取,也能按位置进行数据提取。
下面的代码中行的位置按索引日期设置,列按位置设置。
4.按条件提取(区域和条件值)
除了按标签和位置提取数据以外,还可以按具体的条件取数。
下面使用loc和isin两个函数配合使用,按指定条件对数据进行提取。
使用isin函数对city中的值是否为beijing进行判断。
将isin函数嵌套到loc的数据提取函数中,将判断结果为True数据提取出来。
这里我们把判断条件改为city值是否为beijing和shanghai,如果是,就把这条数据提取出来。
数据提取还可以完成类似数据分列的工作,从合并的数值中提取出指定的数值。
#提取类别的字段的前3个字符
第6章数据筛选
使用与,或,非三个条件配合大于,小于和等于对数据进行筛选,并进行计数和求和。
与Excel中的筛选功能和countifs和sumifs功能相似。
1.按条件筛选(与、或、非)
Excel数据目录下提供“筛选”功能,用于对数据表按不同的条件进行筛选。
Python中使用loc函数配合筛选条件来完成筛选功能。
配合sum和count函数还能实现Excel中sumif和countif函数的功能。
使用“与”条件进行筛选,条件是年龄大于25岁,并且城市为beijing。筛选后只有一条数据符合要求。
使用“或”条件进行筛选,条件是年龄大于25岁,或城市为beijing。
在前面的代码后增加price字段以及sum函数,按筛选后的结果将price字段值进行求和,相当于Excel中sumifs的功能。
使用“非”条件进行筛选,城市不等于beijing。符合条件的数据有4条。将筛选结果按id列进行排序。
在前面的代码后面增加city列,并使用count函数进行计数。相当于Excel中的countifs函数的功能。
还有一种筛选的方式是用query函数。
下面是具体的代码和筛选结果。
在前面的代码后增加price字段和sum函数。对筛选后的price字段进行求和,相当于Excel中的sumifs函数的功能。

























