Python数据处理之(十 一)Pandas 选择数据

版权声明:本文为博主原创文章,转载请注明出处! https://blog.csdn.net/PoGeN1/article/details/84317329

首先先建立一个6X4的矩阵

>>> import pandas as pd
>>> import numpy as np
>>> dates=pd.date_range('20181121',periods=6)
>>> df=pd.DataFrame(np.arange(24).reshape(6,4),index=dates,columns=['A','B','C','D'])
>>> print(df)
             A   B   C   D
2018-11-21   0   1   2   3
2018-11-22   4   5   6   7
2018-11-23   8   9  10  11
2018-11-24  12  13  14  15
2018-11-25  16  17  18  19
2018-11-26  20  21  22  23

一、简单的筛选

如果我们想选取DataFrame中的数据,下面描述了两种途径, 他们都能达到同一个目的:

>>> print(df.A)
2018-11-21     0
2018-11-22     4
2018-11-23     8
2018-11-24    12
2018-11-25    16
2018-11-26    20
Freq: D, Name: A, dtype: int32
>>> print(df['A'])
2018-11-21     0
2018-11-22     4
2018-11-23     8
2018-11-24    12
2018-11-25    16
2018-11-26    20
Freq: D, Name: A, dtype: int32

选择跨越多行或多列:

>>> print(df[0:3])
            A  B   C   D
2018-11-21  0  1   2   3
2018-11-22  4  5   6   7
2018-11-23  8  9  10  11
>>> print(df['20181121':'20181123'])
            A  B   C   D
2018-11-21  0  1   2   3
2018-11-22  4  5   6   7
2018-11-23  8  9  10  11

如果df[3:3]将会是一个空对象。print(df['20181121':'20181123']):选择2018112120181123标签之间的数据,并且包括这两个标签。

二、根据标签 loc

同样我们可以使用标签来选择数据 loc, 本例子主要通过标签名字选择某一行数据, 或者通过选择某行或者所有行(:代表所有行)然后选其中某一列或几列数据。:

>>> print(df.loc['20181122'])
A    4
B    5
C    6
D    7
Name: 2018-11-22 00:00:00, dtype: int32
>>> print(df.loc[:,['A','B']])
             A   B
2018-11-21   0   1
2018-11-22   4   5
2018-11-23   8   9
2018-11-24  12  13
2018-11-25  16  17
2018-11-26  20  21
>>> print(df.loc['20181122',['A','B']])
A    4
B    5
Name: 2018-11-22 00:00:00, dtype: int32

三、根据序列 iloc

另外我们可以采用位置进行选择iloc, 在这里我们可以通过位置选择在不同情况下所需要的数据例如选某一个,连续选或者跨行选等操作。

>>> print(df)
             A   B   C   D
2018-11-21   0   1   2   3
2018-11-22   4   5   6   7
2018-11-23   8   9  10  11
2018-11-24  12  13  14  15
2018-11-25  16  17  18  19
2018-11-26  20  21  22  23
>>> print(df.iloc[3,1])
13
>>> print(df.iloc[3:5,1:3])
             B   C
2018-11-24  13  14
2018-11-25  17  18
>>> print(df.iloc[[1,3,5],1:3])
             B   C
2018-11-22   5   6
2018-11-24  13  14
2018-11-26  21  22

在这里我们可以通过位置选择在不同情况下所需要的数据, 例如选某一个,连续选或者跨行选等操作。

四、根据混合的这两种 ix

当然我们可以采用混合选择 ix, 其中选择’A’’C’的两列,并选择前三行的数据。

>>> print(df.ix[:3,['A','C']])
            A   C
2018-11-21  0   2
2018-11-22  4   6
2018-11-23  8  10

五、通过判断的筛选

最后我们可以采用判断指令 (Boolean indexing) 进行选择. 我们可以约束某项条件然后选择出当前所有数据.

>>> print(df[df.A>8])
             A   B   C   D
2018-11-24  12  13  14  15
2018-11-25  16  17  18  19
2018-11-26  20  21  22  23

下节我们将会讲到Pandas中如何设置值。

猜你喜欢

转载自blog.csdn.net/PoGeN1/article/details/84317329