zoukankan      html  css  js  c++  java
  • 像Excel一样使用Python进行数据分析

    Excel是数据分钟中最常用的工具,通过PythonExcel功能对比,介绍如何使用Python通过函数式编程完成Excel中的数据处理及分析工作。

    Pythonpandas库用于数据处理,我们从1787页的pandas官网文档中总结出最常用的36个函数,通过这些函数介绍如何通过Python完成数据生成和导入,数据清洗,预处理,以及最常见的数据分类,数据筛选,分类汇总,透视等最常见的操作。

    第7章 数据汇总
    本章主要讲解如何对数据进行分类汇总。
    Excel中使用分类汇总和数据透视可以按特定维度对数据进行汇总;
    Python中使用的主要函数是groupby和pivot_table.
    下面分别介绍这两个函数的使用方法。
     
     
     
     

    1生成数据表

    Excel

    常见的生成数据表的方法有两种,第一种是导入外部数据,第二种是直接写入数据。

    Excel中的“文件”菜单中提供了获取外部数据的功能,支持数据库和文本文件和页面的多种数据源导入。

    计算机生成了可选文字:
文 件 
开 始 插 入 页 面 布 局 公 式 
数 哐 审 阅 视 图 
匚 叾 
丷 苜 属 性 
自 Access 自 网 站 自 文 本 自 其 他 来 源 现 有 连 接 全 部 刷 新 
获 取 外

    Python

    Python支持从多种类型的数据导入。

    在开始使用Python进行数据导入之前需要先导入pandas库,为了方便起见,我们也同时导入numpy

    计算机生成了可选文字:
Import numpy a S np 
import pandas a S pd

     

    1.导入数据表

    下面分别是Excelcsv格式文件中导入数据并创建数据表的方法。

    代码是最简模式,里面有很多可选参数设置,例如列名称,索引列,数据格式。

    计算机生成了可选文字:
df=pd. DataFrame()d 。 read_c sv ( 《 name. CSV' ,header=l) ) 
df=pd. DataFrame(pd. read_ExceI ( 《 name. ) )

     

     

    计算机生成了可选文字:
Arguments 
CSV(fiIepath 
h 已 ad 已 「 = 
n m 已 5 
u S 已 匚 01 S = 
m n 1 巴 dupe 匚 015 = T 「 u 巴 
d 已 11m1t 已 
= Non 已 Index 匚 01 = NO 
= F 1 S 已 preflX=NO 
dtype=NO 
t 已 va 1 u = Non 已 fa 1 S 已 va 1 u = NO 
SklP1n1t1 ISP 匚 巳 = F IS 巳 SklprOWS=None 
「 0 5 = NO 
巴 巴 0 default n =T 巴 n +11t 巴 「 = T 「 u 巴 
verbos 巳 = F 1 S 巳 SklP bl n 11 n es =Tru 已 
p 「 5 巴 d at 巴 5 = F 15 巴 
1n* 已 「 format = F 15 已 
已 已 0 d at 已 匚 01 = F 15 已 d at 巳 p 「 S 巳 「 = Non 巳 
dayflrst=FaIse It 巴 「 to 「 = F 15 巴 
匚 h u n 1 记 巴 = NO 
n 巴 匚 0T0 「 巴 5510n = 1 。 
t hou 5 nd 5 = Non 已 d 已 匚 1m 1 = b 
11n 已 t 已 rm1n to 「 = Non 已 quot 已 匚 h 「 = 
已 S 匚 p 已 匚 h 「 = NO 
quotlng=ø, 
d 1 1 巴 Ct = Non 巴 tupl 巴 1 记 巴 匚 015 = F 15 巴 
SklpfOOter=ø, 5k10 foot 巴 「 = doublequote=True 
d 已 11m h1t 已 50 匚 已 = F 15 已 
匚 0T0 匚 t 1 nt 5 = F 15 已 u 5 已 
0 memory=True buffer 
memory m 0 = F 15 巴 f10 t 
unslgned=FaIse 
11 n 巴 5 = 巴 
「 巳 匚 1s10n = 巳

    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: ``' '``

        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 a,b,c 1,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中通过下面的代码来实现。

    计算机生成了可选文字:
Zhen 《 
10 一 A 《 
pd. DataFrame()" Id" : [ 1001 , 1902 , 1003 , 100 ‰ 1005 , 1006 ] , 
"date" : pd 。 date_range( 20130102 
periods=6) , 
''City" : [ 《 Belj Ing 
guangzhou 
《 Shen 
《 shanghai 《 
《 BEIJING 《 ] , 
"age" : [ 23 , 4 ‰ 54 , 3 乙 34 , 32 ] , 
"category" : [ 《 100 一 A' , 1100 一 
1110 一 A' , 1110 一 C 《 
"price" : [ 1200 , np. nan , 2133 , 5433 , np. nan , 4432 ] }, 
columns = [ 'Id 《 
'date' City , 《 age 
'price'])

    计算机生成了可选文字:
1 n [ 45 ] 
: df 
Out [ 45 ] 生 
date 
2213 一 21 一 
City category 
2 
2 
4 
1231 
1232 
1233 
1234 
1235 
2213 一 21 一 22 
2213 一 21 一 23 
24 
2213 一 21 一 25 
2213 一 21 一 25 
8 巳 1 ] Ing 
guangzhou 
She n 记 he n 
shanghai 
日 E I ] ING 
112 一 〔 
32 
5433 · 2

     

    生成数据表的函数是pandas库中的DataFrame函数,数据表一共有6行数据,每行有6个字段。在数据中我们特意设置了一些NA值和有问题的字段,例如包含空格等。

    后面将在数据清洗步骤进行处理。

    后面我们将统一以DataFrame的简称df来命名数据表。

    以上是刚刚创建的数据表,我们没有设置索引列,price字段中包含有NA值,city字段中还包含了一些脏数据。

     

     

     

     

     

    2数据表检查

    本章主要介绍对数据表进行检查。

    Python中处理的数据量通常会比较大,比如纽约的出租车数据和Citibike的骑行数据,其数据量都在千万级,我们无法一目了然地了解数据表的整体情况,必须要通过一些方法来获得数据表的关键信息。

    数据表检查的另一个目的是了解数据的概况,例如整个数据表的大小,所占空间,数据格式,是否有空值和具体的数据内容,为后面的清洗和预处理做好准备。

     

    1.数据维度(行列)

    Excel中可以通过CTRL+向下的光标键,和CTRL+向右的光标键来查看行号和列好。

    Python中使用shape函数来产看数据表的维度,也就是行数和列数,函数返回的结果(6,6)表示数据表有6行,6列。

    下面是具体的代码。

     

    计算机生成了可选文字:
# 查 看 数 据 表 的 维 度 
df. shape 
( 6 , 6 )

     

    2.数据表信息

    使用info函数查看数据表的整体信息,这里返回的信息比较多,包括数据维度、列名称、数据格式和所占空间等信息。

    计算机生成了可选文字:
# 数 据 表 信 息 
df.lnfo() 
<class •pandas. core. frame.DataFrame'> 
Rangelndex: 6 entries, 0 to 5 
Data columns (total 6 COIumnS) : 
id 
date 
City 
category 
age 
pr1ce 
6 non—null int64 
6 non—null datet ime64 [ns] 
6 non—null object 
6 non—null object 
6 non—null int64 
4 non—null f loat64 
dtypes : datetime64[ns] ( 1 ) , float64(1) , 
memo ry usage: 368 . 0 + bytes 
int64(2) , 
object(2)

     

     

    3.查看数据格式

    Excel中通过选中单元格并查看开始菜单中的数值类型来判断数据的格式。

    计算机生成了可选文字:
丹 始 
凶 切 
下 栳 刷 
捲 入 贞 面 布 局 公 式 數 瞎 审 阅 视 图 
开 发 工 目 加 顶 
, 自 动 行 
0 笙 藁 合 后 居 中 -

    Python中使用dtypes函数来返回数据格式。

    dtyps是一个查看数据格式的函数,可以一次性查看数据表中所有数据的格式,也可以指定一列来单独查看。

    计算机生成了可选文字:
# 查 看 数 据 表 各 列 格 式 
df. dtypes 
date 
City 
category 
age 
pr1ce 
主 nt64 
datet me64 [ n s ] 
object 
object 
主 nt64 
f loat64 
dtype : object

     

     

     

    4.查看空值

    Excel中查看空值的方法是使用‘定位条件’功能对数据表中的空值进行定位。

    ‘定位条件’在‘开始’目录下的‘查找和选择’目录中。

    计算机生成了可选文字:
定 位 条 件 
O 批 注 
@ 量 ( 0 
C) 公 式 旧 
数 字 (U) 
文 本 凶 
囝 辑 值 ( G ) 
841 错 误 旧 
0 空 值 
C) 当 前 区 域 
(D 当 前 数 组 ( 
C) 对 象 
C) 行 内 容 差 异 单 元 格 (W ) 
O 列 内 容 差 异 单 元 格 ) 
@ 引 用 单 元 格 旧 
O 从 属 单 元 格 ( D ) 
@ 直 属 (1) 
所 有 级 别 旧 
@ 最 后 一 个 单 元 格 
C) 可 见 单 元 格 (Y) 
@ 条 亻 牛 格 式 (I) 
@ 数 据 验 证 (Y) 
@ 全 部 旧 
相 同 旧 
取 消

     

    IsnullPython中检验空值的函数,返回的结果是逻辑值,包含空值返回True,不包含则返回False

    用户既可以对整个数据表进行检查,也可以单独对某一列进行空值检查。

    计算机生成了可选文字:
1 n [ 59 ] : df•isnull() 
Out [ 59 ] 生 
date 
False 
False 
False 
False 
False 
False 
Ity category 
2 
2 
4 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
True 
False 
F IS 已 
True 
F IS 已

     

    计算机生成了可选文字:
# 检 查 特 定 列 空 值 
0 
1 
2 
3 
4 
5 
Name : 
False 
True 
False 
False 
True 
False 
prlce, 
dtype: 
bool

     

     

    5.查看唯一值

    Excel中查看唯一值得方法是使用‘条件格式’对唯一值进行颜色标记。

    计算机生成了可选文字:
重 复 值 
为 包 含 以 下 类 型 值 的 单 元 格 设 首 格 式 : 
值 , 设 置 为 浅 红 埴 充 色 深 红 色 文 不 
取 消

    Python中是用unique函数查看唯一值。

    Unique是查看唯一值的函数,只能对数据表中的特定列进行检查。

    下面是代码,返回的结果是该列中的唯一值。

    类似与Excel中删除重复项后的结果。

    计算机生成了可选文字:
# 查 看 City 列 中 的 唯 一 值 
array( [ 'Beij ing 
guangzhou 
BEIJING 《 ] , dtype=object) 
1 Shenzhen 
shanghai'

     

     

    6.查看数据表数值

    Python中的Values函数用来查看数据表中的数值。

    以数组的形式返回,不包含表头信息。

    计算机生成了可选文字:
# 查 看 数 据 表 的 值 
df.values 
array( [ [ 1001 , 
Timestamp( 《 2013 一 01 一 02 00 : : 
A 巪 23 , 
1290 . 明 , 
Timestamp( 《 2013 一 01 一 03 00 : : 0 
[ 100 乙 
Timestamp( 《 2013 一 01 一 04 00 : : 0 
[ 1003 , 
10 一 A 巪 5 ‰ 
Timestamp( 《 2013 一 01 一 05 00 : : 0 
Timestamp( 《 2013 一 01 一 06 00 : : 0 
Timestamp( 《 2013 一 01 一 07 00 : : 
Beij ing 
《 199 一 
1100 一 B 《 
44 
guangzhou 
A 《 
2133 . 明 , 
[ 100 ‰ 
3 乙 
5433 . 明 , 
[ 1905 , 
34 , 
[ 1996 , 
3 乙 
4432 . 明 ] , dtype=object) 
1 Shenzhen 
'shanghai' 
BEIJING 
《 110 一 
《 210 一 
《 130 一

     

    7.查看列名称

    计算机生成了可选文字:
co 恤 函 数 用 来 单 独 查 看 数 据 表 中 的 列 名 称 。 
# 查 看 列 名 称 
df.columns 
Index( [ 《 id 《 
object') 
《 category 
dtype=

     

    8.查看前10行数据

    Head()函数用来查看数据表中前N行数据,默认head()显示前10行数据,可以自己设置参数值来确定查看的行数。

    下面的代码中设置查看前3行的数据。

    计算机生成了可选文字:
# 查 看 前 3 行 数 据 
d f . head ( 3 ) 
0 
1 
2 
id 
date 
1001 
2013 . 01 . 02 
1002 
2013 . 01 · 03 
1003 2013 . 01 . 04 
City 
Beijing 
SH 
guangzhou 
category age price 
100 . A 
100 . B 
110 . A 
23 
44 
54 
1200 ℃ 
NaN 
2133 ℃

     

    9.查看后10行数据

    tail函数与head函数相反,用来查看数据表中后N行的数据,默认tail()显示后10行数据,可以自己设置参数值来确定查看的行数。

    下面的代码中设置查看后3行的数据。

    计算机生成了可选文字:
# 查 看 最 后 3 行 
d f . ta iI( 3 )

     

    计算机生成了可选文字:
id 
date 
3 1004 2013 . 01 . 05 
4 1005 2013 . 01 . 06 
5 1006 2013 . 01 . 07 
city 
Shenzhen 
shanghai 
BEIJING 
category age 
1 10-C 
210 · A 
130 · F 
32 
34 
32 
price 
5433 . 0 
NaN 
4432 . 0

     

     

     

     

    3数据表清洗

    本章介绍的是对数据表中的问题进行清洗,主要内容包括对空值、大小写问题、数据格式和重复值的处理。

    这里不包含对数据间的逻辑验证。

     

    1.处理空值(删除或填充)

    我们在创建数据表的时候在price字段中故意设置了几个NA值。

    对于空值的处理方式有很多种,可以直接删除包含空值的数据,也可以对控制进行填充,比如用0填充或者用均值填充。还可以根据不同字段的逻辑对空值进行推算。

    Excel中可以通过‘查找和替换’功能对空值进行处理,将空值统一替换为0或均值。也可以通过‘定位’空值来实现。

    计算机生成了可选文字:
查 找 和 替 懊 
查 伐 (P) 替 P ) 
查 找 内 容 ( N ) : 
替 懊 为 旧 : 
全 部 替 换 
替 换 
查 伐 全 部 
选 顷 田 > > 
查 伐 下 一 个 旧

     

    Python中处理空值的方法比较灵活,可以使用Dropna函数用来删除数据表中包含空值的数据,也可以使用fillna函数对空值进行填充。下面的代码和结果中可以看到使用dropna函数后,包含NA值得两个字段已经不见了。返回的是一个不包含空值的数据表。

    计算机生成了可选文字:
# 删 除 数 据 表 中 含 有 空 值 的 行 
df.dropna(how='any' ) 
id 
1001 
04 
1006 2013 . 01 . 07 
City 
Beijing 
guangzhou 
Shenzhen 
BEIJING 
category age 
0 
2 
3 
5 
date 
2013 £ 1 2 
1003 2013 £ 1 . 
1004 2013 £ 1 . 05 
100 . A 
110 . A 
1 10-C 
130 . F 
23 
54 
32 
32 
price 
1200 ℃ 
2133 ℃ 
5433 ℃ 
4432 ℃

    除此之外,也可以使用数字对空值进行填充,下面的代码使用fillna函数对空值字段填充数字0.

    计算机生成了可选文字:
# 使 用 数 字 真 充 数 据 表 中 空 值 
df.filIna(vaIue=0)

    我们选择填充的方式来处理空值,使用price列的均值来填充NA字段,同样使用fillna函数,在要填充的数值中使用mean函数先计算price列当前的均值,然后使用这个均值对NA进行填充。可以看到两个空值字段显示为3299.5

    计算机生成了可选文字:
# 使 用 pr 跹 e 均 值 对 NA 进 行 填 充 
df [ 《 ] 。 price' ] . mean 0 ) 
9 
1 
2 
3 
4 
1200 . 0 
3299 . 5 
2133 . 0 
5433 . 0 
3299 . 5

     

    计算机生成了可选文字:
伽 t [ 7 · 
date 
2213 一 21 一 
City category 
2 
4 
1232 
1233 
1234 
1235 
2213 一 21 一 23 
24 
2213 一 21 一 25 
2213 一 21 一 25 
8 巳 1 ] Ing 
guangzhou 
Shenzhen 
shanghai 
日 E I ] ING 
123 一 
112 一 二 
112 一 〔 
212 一 层 
4 # 
54 
32 
34 
3299 · 
2133 · 2 
5433 · 2 
3299 ·

     

    2.清理空格

    处理空值,字段中的空格也是数据清洗中一个常见的问题,下面是清楚字符中空格的代码。

    计算机生成了可选文字:
# 清 除 City 字 段 中 的 字 符 空 格 
df['C1ty' ] =df [ 'City 《 ] map(str.strip)

     

     

     

    3.大小写转换

    在英文字段中,字母的大小写不统一也是一个常见的问题。

    Excel中有UPPER,LOWER等函数,Python中也有同名函数用来解决大小写的问题。在数据表的city列中就存在这样的问题。

    我们将city列的所有字母转换为小写。下面是具体的代码和结果。

    计算机生成了可选文字:
city 列 大 小 写 转 换 
df['C1ty' ] =df [ ] . St r . lower()

     

     

    4.更改数据格式

    Excel中通过‘设置单元格格式’功能可以修改数据格式。

    Python中通过astype函数用来修改数据格式。

    计算机生成了可选文字:
单 元 格 格 式 
数 字 对 齐 
貨 币 
会 计 亏 用 
自 分 比 
§ 定 义 
字 体 
边 
填 充 
保 护 
小 数 数 ( D ) : 0 
0 使 用 干 位 分 隔 符 0 圓 
负 数 ( N ) : 
{ 1234 ) 
( 123 引 
1 234 
一 1234 
数 值 格 式 于 一 般 数 字 的 表 示 · 货 币 和 会 计 格 式 则 提 供 货 币 值 计 筻 的 专 用 格 式 ·

    Pythondtype是查看数据格式的函数,与之对应的是astype函数,用来更改数据格式。下面的代码将price字段的值修改为int格式。

    计算机生成了可选文字:
# 更 改 数 据 格 式 
df['pnce'] .astype( 《 int 《 ) 
9 
1 
2 
3 
4 
5 
Name : 
1299 
3299 
2133 
5433 
3299 
4432 
prlce, 
dtype: 
主 nt32

     

    5.更改列名称

    Rename是更改列名称的函数,我们将来数据表中的category列更改为category-size

    下面是具体的代码和更改后的结果。

    计算机生成了可选文字:
# 更 改 列 名 称 
df. rename (columns={ 《 category 《 
《 category—size'}) 
2013 . 01 . 04 guangzhou 
0 
2 
3 
4 
5 
id 
1001 
1003 
1004 
1005 
1006 
date 
2013 . 01 . 02 
1002 2013 . 01 . 03 
2013 . 01 
2013 . 01 . 06 
2013 . 01 . 07 
category-Size age 
. 05 
City 
Beijing 
sh 
Shenzhen 
shanghai 
Beijing 
100 . A 
100 . B 
110 . A 
110-C 
210 . A 
130 . F 
23 
44 
54 
32 
34 
32 
prICe 
1200 
3299 
2133 
5433 
329g 
4432

     

    6.删除重复值

    很多数据表中还包含重复值的问题,Excel的数据目录下有‘删除重复项’的功能,可以用来删除数据表中的重复值。

    默认Excel会保留最先出现的数据,删除后面重复出现的数据。

    计算机生成了可选文字:
目 一 而 
分 列 快 速 填 删 除 验 合 并 计 算 模 拟 分 析 关 系 
重 复 项 证 ,

    Python中使用drop_duplicates函数删除重复值。

    我们以数据表中的city列为例,city字段中存在重复值。

    默认情况下drop_duplicates()将删除后出现的重复值(与Excel逻辑一致)。增加keep='last'参数后将删除最先出现的重复值,保留最后的值。

    下面是具体的代码和比较结果。

    计算机生成了可选文字:
原 始 的 ci 呼 列 中 be 巧 ing 存 在 重 复 , 分 别 在 第 一 位 和 最 后 一 位 。 
df [ 'city' ] 
0 
1 
2 
3 
4 
5 
Name : 
beij ing 
guangzhou 
Shenzhen 
shanghai 
beij Ing 
city, dtype: 
object

    使用默认的drop_duplicates()函数删除重复值,从结果中可以看到第一位的beijing被保留,最后出现的beijing被删除。

    计算机生成了可选文字:
I n [ 108 ] : dfC'city').drop duplicates 0 
Out [ 8 ] 生 
Beijing 
guangzhou 
Shenzhen 
shanghai 
m 巳 : city, dtype 
object

    设置keep='last'参数后,与之前删除重复值的结果相反,第一位出现的beijing被删除,保留了最后一位出现的beijing

    计算机生成了可选文字:
# 删 除 先 出 现 的 重 复 值 
df[ 'city'] .drop—duplicates(keep=' last' ) 
1 
2 
3 
4 
5 
Name : 
guangzhou 
Shenzhen 
shanghai 
belj Ing 
city, dtype: 
Objec

     

    7.数值修改及替换

    数据清洗中最后一个问题是数值修改或替换,Excel中使用“查找和替换”功能就可以实现数值的替换。

    计算机生成了可选文字:
查 找 (D) 替 换 ( P ) 
查 找 内 容 ( N ) . 
替 换 为 旧 . 
找 全 部 (I) 
选 项 田 ” 
查 戊 下 一 个 旧

    Python中使用replace函数实现数据替换。

    数据表中city字段上海存在两种写法,分别为shanghaiSH

    我们使用replace函数对SH进行替换。

    计算机生成了可选文字:
# 数 据 替 换 
df [ ] 。 replace( 'sh 《 
《 shanghai' ) 
0 
1 
2 
3 
4 
5 
Name : 
beij Ing 
shanghai 
guangzhou 
Shenzhen 
shanghai 
beij ing 
City, dtype: 
object

     

     

     

     

     

     

    4  数据预处理

    本章主要讲的是数据的预处理,对清洗完的数据进行整理以便后期的统计和分析工作。

    主要包括数据表的合并,排序,数值分列,数据分组及标记等工作。

     

    1.数据表合并

    首先是对不同的数据表进行合并,我们这里创建一个新的数据表df1,并将dfdf1两个数据表进行合并。

    Excel中没有直接完成数据表合并的功能,可以通过vlookup函数分步实现。

    Python中可以通过merge函数一次性实现。

    下面建立df1数据表,用于和df数据表进行合并。

    计算机生成了可选文字:
1 n [113) . 
1 n [ 且 4 ] · 
Out C114) 
dfl=pd . D t F 「 m 巳 ( { 
· · : [ 1231J 1232J 1233J1234 
gender' : [ 《 male 'female 
'm—point ' : [ 12J 12J 22J42J42 
1235 , 1235J 1237 , 1238 
'male 'female 
4 六 3 六 2 明 } ) 
' fema le 
' ma le 
'female'], 
dfI 
1231 
1232 
1233 
1234 
1235 
1235 
1237 
1238 
m-polnt pay 
7 
gender 
female 
female 
female 
female

    使用merge函数对两个数据表进行合并,合并的方式为inner,将两个数据表中共有的数据匹配到一起生成新的数据表。并命名为df_inner

    计算机生成了可选文字:
# 数 据 表 匹 配 合 并 
df_inner=pd.merge(df,dfl, how=' Inner' 
age 
23 
44 
54 
32 
34 
32 
pnce 
1200 
329g 
2133 
5433 
329g 
4432 
gender m-pomt pay 
0 
2 
3 
4 
5 
id 
date 
1001 
2013 . 01 . 02 
1002 
2013 £ 1 . 03 
1003 
2013 . 01 . 04 
1004 2013 . 01 . 05 
1005 
2013 . 01 . 06 
1006 
2013 . 01 . 07 
City 
beijing 
shanghai 
guangzhou 
Shenzhen 
shanghai 
Beijing 
category 
100 . A 
100 . B 
110 . A 
1 10-C 
210 . A 
130 . F 
male 
female 
male 
female 
male 
female 
12 
20 
40 
40 
40 
Y 
N 
Y 
Y 
N 
Y

    除了inner方式以外,合并的方式还有leftrightouter方式。这几种方式的差别在我其他的文章中有详细的说明和对比。

    计算机生成了可选文字:
df_left=pd 。 merge()f , dfl, how= 《 left ) 
df_right=pd merge(df,dfl, how=' right' ) 
df_outer=pd merge(df,dfl,how='outerl )

     

    2.设置索引列

    完成数据表的合并后,我们对df_inner数据表设置索引列,索引列的功能很多,可以进行数据提取,汇总,也可以进行数据筛选等。

    设置索引的函数为set_index.

    计算机生成了可选文字:
# 设 置 索 引 列 
df n n e r · index( 
date 
id 
1001 
2013 . 01 . 02 
1002 
2013 . 01 . 03 
1003 
2013 . 01 . 04 
1004 
2013 . 01 . 05 
1005 2013 . 01 . 06 
1006 2013 . 01 . 07 
City 
Beijing 
shanghai 
guangzhou 
shenzhen 
shanghai 
be 刂 ing 
category age pnce 
gender 
male 
female 
male 
female 
male 
female 
m-pomt pay 
100 . A 
100 . B 
110 . A 
1 10-C 
210 . A 
130 . F 
23 
44 
54 
32 
34 
32 
1200 
3299 
2133 
5433 
3299 
4432 
10 
12 
20 
40 
40 
40 
Y 
N 
Y 
Y 
N 
Y

     

     

    3.排序(按索引,按数值)

    Excel中可以通过数据目录下的排序按钮直接对数据表进行排序,比较简单。

    计算机生成了可选文字:
排 序 筛 选 《 重 新 
和 筛 选

    Python中需要使用ort_values函数和sort_index函数完成排序。

    Python中,既可以按索引对数据表进行排序,也可以看置顶列的数值进行排序。

    首先我们按age列中用户的年龄对数据表进行排序。

    使用的函数为sort_values.

    计算机生成了可选文字:
# 按 特 定 列 的 值 排 序 
df_lnner. sort_values ( by= [ 《 age 《 ] ) 
age 
23 
32 
32 
34 
44 
54 
price 
1200 
5433 
4432 
3299 
3299 
2133 
gender 
male 
female 
female 
male 
female 
male 
m-pomt pay 
0 
3 
5 
2 
id 
1001 
1006 
4 1005 
date 
2013 . 01 . 02 
1004 2013 . 01 . 05 
2013 . 01 . 07 
2013 1 刁 6 
1002 2013 . 01 . 03 
1003 2013 . 01 . 04 
be 刂 ing 
shenzhen 
be 刂 ing 
shanghai 
shanghai 
guangzhou 
category 
100 . A 
110 . C 
13 F 
210 . A 
10 日 
110 . A 
40 
40 
40 
12 
20 
Y 
Y 
Y 
N 
N 
Y

    Sort_index函数用来将数据表按索引列的值进行排序。

    计算机生成了可选文字:
# 按 索 引 列 排 序 
df n n e sort_index() 
category age 
100 . A 
100 . B 
gender m-potnt pay 
0 
1 
2 
3 
4 
5 
id 
date 
1001 
2013 £ 1 . 02 
1002 
2013 £ 1 . 03 
1003 2013 £ 1 . 04 
1004 2013 £ 1 . 05 
1005 2013 1 . 06 
1006 2013 £ 1 . 07 
be 刂 ing 
shanghai 
guangzhou 110 . A 
shenzhen 1 10-C 
shanghai 
Beijing 
210 . A 
130 . F 
23 
44 
54 
32 
34 
32 
pnce 
1200 
3299 
2133 
5433 
3299 
4432 
male 
female 
male 
female 
male 
female 
10 
12 
20 
40 
40 
40 
Y 
N 
Y 
Y 
N 
Y

     

    4.数据分组

    Excel中可以通过vlookup函数进行近似匹配来完成对数值的分组,或者使用“数据透视表”来完成分组。

    相应的Python中使用where函数完成数据分组。

    where函数用来对数据进行判断和分组,下面的代码中我们对price列的值进行判断,将符合条件的分为一组,不符合条件的分为另一组,并使用group字段进行标记。

    计算机生成了可选文字:
# 如 果 prxce 列 的 值 > 3900 , group 列 显 示 high' 否 则 显 示 low 
df_inner[ 《 g roup 《 ] 
np.where(df_xnner[lpricel] > 3000 , 'high' 
《 10w 
category age 
0 
3 
5 
4 
2 
1 C01 
2013 £ 1 . 02 
1004 2013 . 01 . 05 
1 C06 2013 £ 1 7 
1m5 
2013 . 01 . 06 
1002 
2013 . 01 . 03 
1 C03 2013 £ 1 . 04 
be 刂 ing 
Shenzhen 
Beijing 
shanghai 
shanghai 
guangzhou 
price 
1200 
5433 
4432 
3299 
3299 
2133 
gender 
male 
female 
female 
male 
female 
male 
m-polnt pay group 
100 . A 
110 ℃ 
130 . F 
210 . A 
1 00 . B 
110 . A 
23 
32 
32 
34 
44 
54 
40 
40 
40 
12 
20 
Y 
low

    除了where函数以外,还可以对多个字段的值进行判断后对数据进行分组,下面的代码中对city列等于beijing并且price列大于等于4000的数据标记为1.

     

    计算机生成了可选文字:
1 n [136) 
Inn 已 「 [ 
1 n (137] 
Out [ 137 ] 生 
date 
2213 一 21 一 
5 Ign 
2213 一 21 
2213 一 21 
City 
Beijing 
shanghai 
guangzhou 
Shenzhen 
shanghai 
Beijing 
. wh 已 「 巳 ( (df 
category 
123 一 
112 一 〔 
212 一 层 
Inn 已 「 0 ty ' ] : 
Beijing ')&(df innerC'price')>4øøø),1,np.nan) 
2 
2 
4 
1231 
1232 
1233 
1235 
1235 
5 Ign 
m-polnt pay group 
12 high 
2213 一 21 一 23 
2213 一 21 一 25 
一 22 
24 
一 27 
4 # 
32 
34 
32 
3299 
5433 
3299 
4432 
gender 
female 
female 
female

     

    计算机生成了可选文字:
I n [ 14 明 : df inner.10cC((df n 已 「 0 ty ' ] : 
Beijing' )&(df nn 已 「 [ ' price ' ] > : 4233 ) ) , 
5 gn2 ' ] : 
1 n [ 篁 4 篁 ] 
Out C141) 生 
date 
2213 一 21 一 
City category 
2 
2 
4 
1231 
1232 
1233 
1235 
1235 
5 Ign 
2213 一 21 
2213 一 21 
4 # 
32 
34 
32 
3299 
5433 
3299 
4432 
gender 
female 
female 
female 
m-polnt pay group 
12 high 
2213 一 21 一 23 
2213 一 21 一 25 
一 22 
24 
一 27 
Beijing 
shanghai 
guangzhou 
Shenzhen 
shanghai 
Beijing 
123 一 
112 一 〔 
212 一 层 
51gn2

     

    5.数据分列

    与数据分组相反的是对数值进行分列,Excel中的数据目录下提供‘分列’功能。

    Python中使用split函数实现分列。

    计算机生成了可选文字:
分 列 
[ 二 0 
速 埴 充 删 除 数 据 验 合 并 计 篡 模 拟 分 析 关 系 
重 顶 证 , 
数 据 工 具

    在数据表中category列中的数据包含有两个信息,前面的数字为类别id,后面的字母为size值。中间以连字符进行联结。我们使用split函数对这个字段进行拆分,并将拆分后的数据表匹配回原数据表中。

    计算机生成了可选文字:
# 对 category 字 段 的 值 依 次 进 行 分 列 , 并 创 建 数 据 表 , 索 引 值 为 df 一 inner 的 索 引 列 , 列 
名 称 为 category 和 Size 
pd.DataFrame( ( x . split( 《 
《 ) for x in df_inner[ 'category'] ) , index=d 
f_inner. index, columns=[ 《 category' , size' ] )

     

    计算机生成了可选文字:
I n [ 142 ] : pd.DataFrame((x.sp1it('-') for x in 
df nn 「 [ 'category ), index=df nn 已 「 . index, columns=C ' category 
Out [ 142 ] 。 
category 51 记 已

     

    计算机生成了可选文字:
# 将 完 成 分 列 后 的 数 据 表 与 原 df 一 主 nner 数 据 表 进 行 匹 配 
df_inner=pd merge(df_inner, split, right 
index=True, 
left 
index=Tru 
category_l Size 
0 
3 
5 
4 
2 
id 
date 
1 1 
2C13 . 01 . 02 
1004 
2C13 . 丁 . 05 
1006 2013 . 丁 . 07 
1005 2013 . 01 . 06 
1 開 2 
2C13 . 01 . 03 
1 3 2013 . 01 . 04 
City 
be 刂 ing 
shenzhen 
Beijing 
shanghai 
shanghai 
guangzhou 
category age 
price 
1200 
5433 
4432 
3299 
3299 
2133 
gender 
male 
female 
female 
male 
female 
male 
m-polnt pay group Sign 
100 . A 
1 10-C 
130 . F 
210 . A 
10 8 
110 . A 
23 
32 
32 
34 
44 
54 
40 
40 
40 
12 
20 
Y 
Y 
N 
N 
Y 
《 ow 
high 
high 
high 
《 ow 
NaN 
NaN 
1 ℃ 
NaN 
NaN 
NaN 
100 
1 10 
130 
210 
100 
1 10 
A 
C 
F 
A 
8 
A

     

     

     

     

    5数据提取

    数据提取,也就是数据分析中最常见的一个工作。

    这部分主要使用3个函数,即loc,ilocix

    loc函数按标签值进行提取;

    iloc函数按位置进行提取;

    ix函数可以同时按标签和位置进行提取。

     

    下面介绍每一种函数的使用方法。

    1.按标签提取loc函数

    loc函数按数据表的索引标签进行提取,下面的代码中提取了索引列为3的单条数据。

    计算机生成了可选文字:
# 按 索 引 提 取 单 行 的 数 值 
df_lnner. IOC [ 3 ] 
id 
date 
City 
category 
age 
pr1ce 
gender 
m—P01nt 
pay 
group 
Sign 
category_ 
sIze 
Name : 3 , 
1004 
2013 一 01 一 05 00 : 00 : 00 
Shenzhen 
110 一 C 
5433 
fema le 
40 
Y 
high 
NaN 
1 
110 
C 
dtype: 
object

    使用冒号可以限定提取数据的范围,冒号前面为开始的标签值,后面为结束的标签值。

    下面提取了0-5的数据行。

    计算机生成了可选文字:
# 按 索 引 提 取 区 域 行 数 值 
df_inner. 10 c [ 0 : 5 ] 
category 
100 . A 
1 10-C 
130 . F 
age 
23 
32 
32 
pnce 
1200 
5433 
4432 
gender 
male 
female 
female 
m-polnt 
10 
40 
40 
pay 
Y 
Y 
group 
《 ow 
high 
Slgn 
NaN 
NaN 
category_l size 
0 
3 
5 
id 
date 
1001 
2013 . 01 . 02 
1004 2013 . 01 . 05 
1006 2013 £ 1 7 
City 
Beijing 
Shenzhen 
Beijing 
1 
1 10 
A 
C 
F

    Reset_index函数用于恢复索引,这里我们重新将date字段的日期设置为数据表的索引,并按日期进行数据提取。

    计算机生成了可选文字:
# 重 设 索 引 
df inner 
index id 
· reset 
date 
2013 . 01 
1004 2013 . 01 . 05 
1006 2013 . 01 
1005 2013 . 01 . 06 
1002 2013 . 01 
1003 2013 . 01 . 04 
index( ) 
City 
Beijing 
Shenzhen 
be 刂 ing 
shanghai 
shanghai 
guangzhou 
category 
100 . A 
1 10 ℃ 
130 . F 
210 . A 
100 . B 
1 10-A 
age 
23 
32 
32 
34 
44 
54 
pnce 
120D 
5433 
4432 
32g9 
32g9 
2133 
gender 
male 
female 
female 
male 
female 
male 
m-polnt 
10 
40 
40 
40 
12 
20 
pay 
Y 
Y 
N 
N 
Y 
group 
low 
high 
high 
high 
low 
category_l size 
1001 
1 3 
. 02 
. 07 
. 03 
NaN 
NaN 
1 ℃ 
NaN 
NaN 
NaN 
100 
1 10 
130 
210 
100 
1 10 
A 
C 
F 
A 
A

     

    计算机生成了可选文字:
# 设 置 日 期 为 索 引 
df inner=df inner. set index( 'date') 
gender In-point pay group Sign 
category_l Size 
date 
2013 · 0 不 02 
2013 1 庵 05 
2013 1 7 
2013 . 01 . 06 
2013 · 01 · 03 
2013 庵 01 庵 04 
id 
1 羽 1 
1004 
1006 
1005 
1 2 
1 3 
city 
be 刂 ing 
shenzhen 
beijing 
shanghai 
shanghai 
guangzhou 
category age 
10 A 
110 ℃ 
130 . F 
210 . A 
10 B 
110- A 
23 
32 
32 
34 
44 
54 
price 
1200 
5433 
4432 
3299 
3299 
2133 
female 
female 
male 
female 
male 
10 
40 
40 
40 
12 
20 
Y 
Y 
Y 
N 
N 
Y 
low 
high 
high 
high 
high 
low 
NaN 
NaN 
1 旧 
NaN 
NaN 
NaN 
100 
110 
130 
210 
100 
1 10 
A 
C 
A 
A

     

    使用冒号限定提取数据的范围,冒号前面为空表示从0开始。

    提取所有201314日以前的数据。

    计算机生成了可选文字:
# 提 取 4 日 之 前 的 所 有 数 据 
df_inner[: 《 2013 一 01 一 04 《 
city 
Beijing 
shanghai 
guangzhou 
category age price 
gender m-point pay group sign 
ca 怡 go 吖 一 1 size 
2013 1 刁 2 
2013 “ 01 “ 03 
2013 . 01 刁 4 
id 
0 001 
1002 
1003 
0 00 . A 
1 0 3 
110 . A 
23 
44 
54 
12 羽 
3299 
2133 
male 
ma 
male 
12 
20 
N 
Y 
high 
《 ow 
NaN 
NaN 
102 
110 
A 
A

     

    2.按位置提取 iloc函数

    使用iloc函数按位置对数据表中的数据进行提取,这里冒号前后的数字不再是索引的标签名称,而是数据所在的位置,从0开始。

    计算机生成了可选文字:
使 用 iloc 按 位 置 区 域 提 取 数 据 
df_inner.iIoc[:3, : 2 ] 
date 
2013 . 01 . 02 
2013 · 01 “ 05 
2013 1 “ 0 / 
id 
1001 
1004 
1006 
city 
Beijing 
shenzhen 
beijing

    iloc函数除了可以按区域提取数据,还可以按位置逐条提取,前面方括号中的0,2,5,表示数据所在行的位置,后面方括号中的数表示所在列的位置。

    计算机生成了可选文字:
1 n [ 巧 9 ] · 
Out [ 篁 59 ] : 
date 
2213 一 21 一 22 
2213 一 21 一 24 
2213 一 21 一 27 
df nn 已 「 . iloc [ Cø, 2, 5 ] 
1223 
2133 
4 # 32 
gender 
female

     

    3.按标签和位置提取 ix函数

    ixlociloc的混合,既能按索引标签提取,也能按位置进行数据提取。

    下面的代码中行的位置按索引日期设置,列按位置设置。

    计算机生成了可选文字:
# 使 用 按 索 引 标 签 和 位 置 混 合 提 取 数 据 
df_inner. ix [ : 《 2013 一 01 一 03 《 , : 4 ] 
id 
date 
City 
category age 
2013 . 01 . 02 1001 Beijing 
100 . A 
2013 “ 01 刁 3 1C02 shanghai 1 開 -8 
23 
44

     

    4.按条件提取(区域和条件值)

    除了按标签和位置提取数据以外,还可以按具体的条件取数。

    下面使用locisin两个函数配合使用,按指定条件对数据进行提取。

    使用isin函数对city中的值是否为beijing进行判断。

    计算机生成了可选文字:
I n [ 162 ] : df n 已 「 0 ty ' ] . ( [ 
Out [ 2 ] : 
Beijing')) 
date 
2213 一 21 一 22 
2213 一 21 一 23 
2213 一 21 一 24 
2213 一 21 一 25 
2213 一 21 一 25 
2213 一 21 一 27 
Name : 
City 
False 
False 
False 
False 
True 
, dtype. bool

    isin函数嵌套到loc的数据提取函数中,将判断结果为True数据提取出来。

    这里我们把判断条件改为city值是否为beijingshanghai,如果是,就把这条数据提取出来。

    计算机生成了可选文字:
# 先 判 断 City 列 里 是 否 包 含 belj Ing 和 shanghai, 然 后 将 复 合 条 件 的 数 据 提 取 出 来 。 
df_inner. IOC [df_xnner[ 《 ] 。 1Sin( 时 beij ing 
'shanghai'] ) ] 
date 
2013 “ 01 庵 02 
2013 . 01 . 07 
2013 “ 0 不 06 
2 仍 3 . 01 . 03 
id 
City 
10D1 
be 刂 ing 
1006 
Beijing 
10D5 
shanghai 
1002 shanghai 
category age price 
gender 
male 
female 
male 
female 
m-polnt pay group Sign 
category_l Size 
100-A 
130 . F 
210 . A 
耗 0 旧 
23 
32 
34 
44 
1200 
4432 
32g9 
3299 
10 
40 
40 
12 
Y 
Y 
N 
N 
low 
high 
high 
high 
NaN 
1 ℃ 
NaN 
NaN 
1 
130 
210 
耗 0 
A 
F 
A

    数据提取还可以完成类似数据分列的工作,从合并的数值中提取出指定的数值。

    计算机生成了可选文字:
category=df_xnner [ 《 category 《 ] 
0 
3 
5 
4 
1 
2 
199 一 A 
119 一 C 
130 一 F 
210 一 A 
199 一 B 
110 一 A 
Name : category, dtype: object 
# 提 取 前 三 个 字 符 , 并 生 成 数 据 表 
pd.DataFrame(category.str[:3] )

     

    计算机生成了可选文字:
1 n [ 5 ] · 
1 n [ 7 ] · 
Out [ 67 ] : 
date 
2213 一 21 一 22 
2213 一 21 一 23 
2213 一 21 一 24 
2213 一 21 一 25 
2213 一 21 一 25 
2213 一 21 一 27 
category=df nn 已 「 [ ' category x') 
category 
category x, dtype: object 
I n [ 168 ] : pd .DataFrame(category st 「 [ : 明 ) 
伽 t [ 篁 68 ] · 
category x 
date 
2213 一 21 一 22 
2213 一 21 一 23 
2213 一 21 一 24 
2213 一 21 一 25 
2213 一 21 一 25 
2213 一 21 一 27

    #提取类别的字段的前3个字符

     

     

    6数据筛选

    使用与,或,非三个条件配合大于,小于和等于对数据进行筛选,并进行计数和求和。

    Excel中的筛选功能和countifssumifs功能相似。

     

    1.按条件筛选(与、或、非)

    Excel数据目录下提供“筛选”功能,用于对数据表按不同的条件进行筛选。

    计算机生成了可选文字:
馭 i 不 
重 新 应 用 
廴 排 序 筛 选 
高 级 
排 序 和 师 辶 一

    Python中使用loc函数配合筛选条件来完成筛选功能。

    配合sumcount函数还能实现Excelsumifcountif函数的功能。

    使用“与”条件进行筛选,条件是年龄大于25岁,并且城市为beijing。筛选后只有一条数据符合要求。

    计算机生成了可选文字:
I n [ 172 ] : df nn 已 「 . loc [ ()f inne 
0 id ity g 巴 
1 n [ 丷 3 ] · 
Out [ 篁 72 ] : 
date 
「 [ 的 >25)&(df n 已 「 0 ty ' ] : 
Beijing'), 
'category 'gender']] 
City 
2213 一 21 一 27 1235 Beijing 
g 巳 category 
32 
gender 
femalel

    使用“或”条件进行筛选,条件是年龄大于25岁,或城市为beijing

    计算机生成了可选文字:
I n [ 173 ] : df 
CIt-y 
Out [ 篁 73 ] : 
date 
2213 一 21 一 22 
2213 一 21 一 23 
2213 一 21 一 24 
2213 一 21 一 25 
2213 一 21 一 25 
2213 一 21 一 27 
.10cC()f inne 
'category 'gender']] 
Beijing'), 
1231 
1232 
1233 
1234 
1235 
1235 
City 
Beijing 
shanghai 
guangzhou 
Shenzhen 
shanghai 
g 巳 category 
23 
4 # 
54 
34 
gender 
female 
female 
female

     

    在前面的代码后增加price字段以及sum函数,按筛选后的结果将price字段值进行求和,相当于Excelsumifs的功能。

    计算机生成了可选文字:
I n [ 175 ] : df nn 已 「 . loc [ ()f nn 已 「 0 s 巴 
category , 'gender 
匚 It-y S 巴 
Out [ 篁 75 ] : 19795 · 2 
的 刃 5 》 ()f inne 
「 [ 《 city 
'beijing'), 
price ] ] . 50 「 t values (by= g

     

    使用“非”条件进行筛选,城市不等于beijing。符合条件的数据有4条。将筛选结果按id列进行排序。

    计算机生成了可选文字:
I n [ 178 ] : df 
Clty 
Out [ 篁 78 ] · 
date 
2213 一 21 一 23 
2213 一 21 一 24 
2213 一 21 一 25 
2213 一 21 一 25 
loc Cdf inner( ty !='beijing 
'category', 'gender']] · 50 「 t values (by 
1232 
1233 
1234 
1235 
City 
shanghai 
guangzhou 
Shenzhen 
shanghai 
g 巳 category 
4 # 
54 
34 
gender 
female 
female

     

    在前面的代码后面增加city列,并使用count函数进行计数。相当于Excel中的countifs函数的功能。

    计算机生成了可选文字:
I n [ 179 ] : df 
category , ' g nde 「 ] . 50 「 t values (by= 
CIt-y 
Out [ 179 ] : 4 
loc Cdf nn 已 「 [ ty 的 ! : 
Beijing 
'id').city•count()

     

    还有一种筛选的方式是用query函数。

    下面是具体的代码和筛选结果。

    计算机生成了可选文字:
1 n [ 2 % ] · 
date 
2213 一 21 一 22 
2213 一 21 一 23 
2213 一 21 一 25 
2213 一 21 一 27 
date 
2213 一 21 一 23 
df nn 已 「 
1231 
1232 
1235 
1235 
5 Ign 
City category x 
''shanghai") ') 
gender 
Beijing 
shanghai 
shanghai 
Beijing 
123 一 
212 一 层 
m-polnt pay group 
12 Y IOW 
12 high 
4 # 
34 
32 
3299 
3299 
4432 
female 
female 
51gn2 categoryJ 51 记 已

    在前面的代码后增加price字段和sum函数。对筛选后的price字段进行求和,相当于Excel中的sumifs函数的功能。

    计算机生成了可选文字:
# 对 筛 选 后 的 结 果 按 pr 跹 e 进 行 求 和 
df inner.query( 'City 
["beijing" 
12230 
" shanghai" 
) 思 price. sum( )

     

     

     

     

     

     

     

    1.分类汇总
    Excel的数据目录下提供了“分类汇总”功能,可以按指定的字段和汇总方式对数据表进行汇总。
    Python中通过groupby函数完成相应的操作,并可以支持多级分类汇总。
     groupby函数是进行分类汇总的函数,使用方法很简单,指定要分组的列名称就可以,也可以同时指定多个列名称,groupby按列名称出现的顺序进行分组。同时要制定分组后的汇总方式,常见的是计数和求和两种。
     可以在groupby中设置列名称来对特定的列进行汇总。下面的代码中按城市对id字段进行汇总计数。
     在前面的基础上增加第二个列名称,分布对city和size两个字段进行计数汇总。
     除了计数和求和外,还可以对汇总后的数据同时按多个维度进行计算,下面的代码中按城市对price字段进行汇总,并分别计算price的数量,总金额和平均金额。
     
     
    2.数据透视
    Excel中插入目录下提供“数据透视表”功能对数据表按特定维度进行汇总。
     
    Python中也提供了数据透视表功能。通过pivot_table函数实现同样的效果。
    数据透视表也是常用的一种数据分类汇总方式,并且功能上比groupby要更强大一些。
    下面的代码中设定city为行字段,size为列字段,price为值字段。
    分别计算price的数量和金额并且按行与列进行汇总。
     
     
     
     
    第8章 数据统计
    本章主要介绍数据采样,标准差,协方差和相关系数的使用方法。
    1.数据采样
    Excel的数据分析功能中提供了数据抽样的功能,如下路所示。
     
    Python通过sample函数完成数据采样。
    sample函数是进行数据采样的函数,设置n的数量就可以了。
    函数自动返回采集的结果。
     
    Weights参数是采样的权重,通过设置不同的权重可以更改采样的结果,权重高得数据将更有希望被选中。
    这里手动设置6条数据的权重值。将前面4个设置为0,后面两个设置为0.5.
     
     sample函数中还有一个参数replace,用来设置采样后是否放回。
     
     
    2.描述统计
    Excel中的数据分析中提供了描述统计的功能。
     
    Python中可以通过describe函数对数据进行描述统计。
    describe函数是进行描述统计的函数,自动生成数据的数量,均值,标准差等数据。
    下面的代码中对数据表进行描述统计,并使用roung函数设置结果显示的小数位。并对结果数据进行转置。
     
    3.标准差
    Python中std函数用来计算特定数据列的标准差。
     
    4.协方差
    Excel中的数据分析功能中提供协方差的计算;
     
    Python中通过cov函数计算两个字段或数据表中各字段间的协方差。
    cov函数用来计算两个字段间的协方差,可以支队特定字段进行计算,也可以对整个数据表中各个列之间进行计算。
     
     
    5.相关分析
    Excel的数据分析功能中提供了相关系数的计算功能;
    Python中则通过corr完成相关分析的操作,并返回相关系数。
    corr函数用来计算数据间的相关系数,可以单独对特定数据进行计算,也可以对整个数据表中各个列进行计算。
    相关系数在-1和1之间,接近1为正相关,接近-1为负相关,0为不相关。
     
     
     
    第9章 数据输出
    处理和分析完的数据可以输出为xlsx格式和csv格式。
     
    1.写入Excel
     2.写入csv
     
     
     
     
    案例:990万次骑行:纽约自行车共享系统分析
     
  • 相关阅读:
    7 重排序与happens-before
    6 Java内存模型基础知识
    5 Java线程间的通信
    Java线程的状态及主要转化方法
    《The Boost C++ Libraries》 第一章 智能指针
    python通过swig调用静态库
    使用gdb调试
    Rsync服务部署使用
    UNP学习总结(二)
    read()函数的困惑
  • 原文地址:https://www.cnblogs.com/zoe233/p/7026229.html
Copyright © 2011-2022 走看看