Pandas学习笔记

笨办法学分析[05]pandas常用操作(二)

2018-10-10  本文已影响26人  一起学分析
22.缺失值判断: s.isnull()

isnull()方法可以对缺失值NaN值进行判断,返回对Series或DataFrame的每个元素的判定结果,存在缺失值。但不能识别空值,空格等。
notnull()是isnull()的否定式。

In [2]: s=pd.Series(['a','b','c','',' ',np.nan,None])

In [3]: s
Out[3]: 
0       a
1       b
2       c
3        
4        
5     NaN
6    None
dtype: object

In [4]: s.isnull()
Out[4]: 
0    False
1    False
2    False
3    False
4    False
5     True
6     True
dtype: bool

#对dataframe进行判断
In [5]: df=pd.DataFrame([['a','b','c','',' ',np.nan,None],
   ...:                  ['E','F',np.nan,'H','I',3,6]],index=['a1','a2']).T

In [6]: df
Out[6]: 
    a1   a2
0    a    E
1    b    F
2    c  NaN
3         H
4         I
5  NaN    3
6  NaN    6

In [7]: df.isnull()
Out[7]: 
      a1     a2
0  False  False
1  False  False
2  False   True
3  False  False
4  False  False
5   True  False
6   True  False
23.删除缺失值: s.dropna() / df.dropna()
In [8]: s
Out[8]: 
0       a
1       b
2       c
3        
4        
5     NaN
6    None
dtype: object

In [9]: s.dropna()
Out[9]: 
0    a
1    b
2    c
3     
4     
dtype: object

#对于DataFrame,dropna还有可选参数
In [10]: df2=pd.DataFrame([['a','b','c','',' ',np.nan,None],
    ...:                  ['E','F',np.nan,'H','I',3,np.nan]],index=['a1','a2']).T

In [11]: df2
Out[11]: 
    a1   a2
0    a    E
1    b    F
2    c  NaN
3         H
4         I
5  NaN    3
6  NaN  NaN

In [12]: df2.dropna()
Out[12]: 
  a1 a2
0  a  E
1  b  F
3     H
4     I

In [13]: df2.dropna(how='all')
Out[13]: 
    a1   a2
0    a    E
1    b    F
2    c  NaN
3         H
4         I
5  NaN    3
24.填充缺失值: s.fillna() / df.fillna()
In [14]: df2
Out[14]: 
    a1   a2
0    a    E
1    b    F
2    c  NaN
3         H
4         I
5  NaN    3
6  NaN  NaN

#直接填充值
In [15]: df2.fillna(888)
Out[15]: 
    a1   a2
0    a    E
1    b    F
2    c  888
3         H
4         I
5  888    3
6  888  888

#使用method参数
In [16]: df2.fillna(method='ffill')
Out[16]: 
  a1 a2
0  a  E
1  b  F
2  c  F
3     H
4     I
5     3
6     3

#可以使用计算值填充数据
In [17]: df2.fillna(df.count())
Out[17]: 
  a1 a2
0  a  E
1  b  F
2  c  6
3     H
4     I
5  5  3
6  5  6
25.重复值判定: s.duplicated() / df.duplicated()
In [24]: s2=pd.Series(['A','A','B','b'])

In [25]: s2
Out[25]: 
0    A
1    A
2    B
3    b
dtype: object

In [26]: s2.duplicated()
Out[26]: 
0    False
1     True
2    False
3    False
dtype: bool

In [27]: df4=pd.DataFrame([['A','A','B','b'],
    ...:                   ['A','C','b','b'],
    ...:                   ['e','d','f','b'],
    ...:                   ['e','d','f','b']],columns=['a1','a2','a3','a4'])

In [28]: df4
Out[28]: 
  a1 a2 a3 a4
0  A  A  B  b
1  A  C  b  b
2  e  d  f  b
3  e  d  f  b

In [29]: df4.duplicated()
Out[29]: 
0    False
1    False
2    False
3     True
dtype: bool
26.删除重复值: s.drop_duplicates() / df.drop_duplicates()
In [30]: s2
Out[30]: 
0    A
1    A
2    B
3    b
dtype: object

In [31]: s2.drop_duplicates()
Out[31]: 
0    A
2    B
3    b
dtype: object

In [32]: df4
Out[32]: 
  a1 a2 a3 a4
0  A  A  B  b
1  A  C  b  b
2  e  d  f  b
3  e  d  f  b

In [33]: df4.drop_duplicates()
Out[33]: 
  a1 a2 a3 a4
0  A  A  B  b
1  A  C  b  b
2  e  d  f  b
In [34]: df4.drop_duplicates(keep=False)
Out[34]: 
  a1 a2 a3 a4
0  A  A  B  b
1  A  C  b  b

#指定列进行重复判断
In [62]: df4.drop_duplicates(subset=['a1','a4'])
Out[62]: 
  a1 a2 a3 a4
0  A  A  B  b
2  e  d  f  b
27.数据分类(映射): s.map(dict)

使用map()可以利用字典完成对数据序列的映射,在很多工作中会用到,例如对商品进行归类、把代号转换成文字内容等。

In [13]: df=pd.DataFrame([list('abcdefgh'),
    ...:                  [15,24,33,13,53,21,31,91],
    ...:                  [1,2,3,4,1,2,2,2]],index=['name','age','city']).T

In [14]: df
Out[14]: 
  name age city
0    a  15    1
1    b  24    2
2    c  33    3
3    d  13    4
4    e  53    1
5    f  21    2
6    g  31    2
7    h  91    2

#通过字典完成对用户名单的性别映射
In [15]: sex={'a':'男',
    ...:      'b':'女',
    ...:      'c':'男',
    ...:      'd':'男',
    ...:      'e':'女',
    ...:      'f':'男',
    ...:      'g':'未知',
    ...:      'h':'男',}

In [16]: df['sex']=df['name'].map(sex)

In [17]: df
Out[17]: 
  name age city sex
0    a  15    1   男
1    b  24    2   女
2    c  33    3   男
3    d  13    4   男
4    e  53    1   女
5    f  21    2   男
6    g  31    2  未知
7    h  91    2   男
28.替换值: s.replace() / df.replace()
In [19]: df
Out[19]: 
  name age city sex
0    a  15    1   男
1    b  24    2   女
2    c  33    3   男
3    d  13    4   男
4    e  53    1   女
5    f  21    2   男
6    g  31    2  未知
7    h  91    2   男

#将city的代号对应到城市名称
In [20]: df['city']=df['city'].replace([1,2,3,4],['北京','上海','广州','重庆'])
In [21]: df
Out[21]: 
  name age city sex
0    a  15   北京   男
1    b  24   上海   女
2    c  33   广州   男
3    d  13   重庆   男
4    e  53   北京   女
5    f  21   上海   男
6    g  31   上海  未知
7    h  91   上海   男
29.离散化和面元划分(数据分段): pd.cut(s,bins,labels)
In [13]: ages = [20, 22, 25, 27, 21, 23, 37, 31, 61, 45, 41, 32]
    ...: bins=[10,18,25,45,70,100]
    ...: labels=['少年','青年','壮年','中年','老年']
    ...: cats=pd.cut(ages,bins,labels=labels)

In [14]: cats
Out[14]: 
[青年, 青年, 青年, 壮年, 青年, ..., 壮年, 中年, 壮年, 壮年, 壮年]
Length: 12
Categories (5, object): [少年 < 青年 < 壮年 < 中年 < 老年]

In [15]: pd.value_counts(cats)
Out[15]: 
壮年    6
青年    5
中年    1
老年    0
少年    0
dtype: int64
30.异常值检测和过滤(替换异常值)
In [17]: data=pd.DataFrame(np.random.randn(1000,4))

In [18]: data.describe()
Out[18]: 
                 0            1            2            3
count  1000.000000  1000.000000  1000.000000  1000.000000
mean      0.004810    -0.027545    -0.045605    -0.016705
std       1.004290     1.021424     0.994457     0.949196
min      -3.206029    -3.584745    -3.558081    -2.728175
25%      -0.687393    -0.756027    -0.701376    -0.646029
50%       0.052037    -0.061157    -0.062893     0.005118
75%       0.658388     0.672714     0.608198     0.631999
max       3.658853     3.077312     3.619713     2.838411

In [19]: data[(np.abs(data)>3).any(axis=1)]
Out[19]: 
            0         1         2         3
30  -0.338671  1.377560 -3.052083  1.129186
180 -1.553646 -3.200527  0.753505  1.962077
192 -0.412346 -2.276327 -3.558081  0.434918
254  1.161989 -3.584745 -0.370215  0.353072
321 -0.936188 -1.618777  3.619713  0.517175
338 -0.458360  3.077312 -0.195628 -0.476386
404 -1.335868 -3.073252  0.484003  0.013251
447 -3.116901  1.428209  0.042362  1.424448
518 -0.978763 -0.343995 -3.084647  0.379374
644  3.042225 -1.468389  0.261914 -0.663178
696  3.658853 -1.206324 -0.810575 -1.672725
711 -3.206029  0.454197 -0.214890  0.118297
717 -0.749071  3.075002  0.774330 -0.593757

#将绝对值大于3的数据限制在3以内
In [20]: data[np.abs(data)>3]=np.sign(data)*3

In [21]: data.describe()
Out[21]: 
                 0            1            2            3
count  1000.000000  1000.000000  1000.000000  1000.000000
mean      0.004432    -0.026839    -0.045529    -0.016705
std       1.000979     1.018271     0.990127     0.949196
min      -3.000000    -3.000000    -3.000000    -2.728175
25%      -0.687393    -0.756027    -0.701376    -0.646029
50%       0.052037    -0.061157    -0.062893     0.005118
75%       0.658388     0.672714     0.608198     0.631999
max       3.000000     3.000000     3.000000     2.838411

31.计算指标/哑变量(选项的二分法转换): pd.get_dummies()
In [22]: df = pd.DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'b'],
    ...:     'data1': [1,2,3,4,5,5]})

In [23]: df
Out[23]: 
  key  data1
0   b      1
1   b      2
2   a      3
3   c      4
4   a      5
5   b      5

In [24]: pd.get_dummies(df['key'])
Out[24]: 
   a  b  c
0  0  1  0
1  0  1  0
2  1  0  0
3  0  0  1
4  1  0  0
5  0  1  0

#使用prefix添加前缀,并合并其他数据
In [25]: dummies = pd.get_dummies(df['key'], prefix='key')
    ...: df[['data1']].join(dummies)
Out[25]: 
   data1  key_a  key_b  key_c
0      1      0      1      0
1      2      0      1      0
2      3      1      0      0
3      4      0      0      1
4      5      1      0      0
5      5      0      1      0
32.字符串操作方法
33.DataFrame的索引操作
>>> frame = pd.DataFrame({'a': range(7), 'b': range(7, 0, -1),
...     'c': ['one', 'one', 'one', 'two', 'two','two', 'two'],
...     'd': [0, 1, 2, 0, 1, 2, 3]})
>>> frame
   a  b    c  d
0  0  7  one  0
1  1  6  one  1
2  2  5  one  2
3  3  4  two  0
4  4  3  two  1
5  5  2  two  2
6  6  1  two  3
>>> frame.unstack()
a  0      0
   1      1
   2      2
   3      3
   4      4
   5      5
   6      6
b  0      7
   1      6
   2      5
   3      4
   4      3
   5      2
   6      1
c  0    one
   1    one
   2    one
   3    two
   4    two
   5    two
   6    two
d  0      0
   1      1
   2      2
   3      0
   4      1
   5      2
   6      3
dtype: object
>>> frame.stack()
0  a      0
   b      7
   c    one
   d      0
1  a      1
   b      6
   c    one
   d      1
2  a      2
   b      5
   c    one
   d      2
3  a      3
   b      4
   c    two
   d      0
4  a      4
   b      3
   c    two
   d      1
5  a      5
   b      2
   c    two
   d      2
6  a      6
   b      1
   c    two
   d      3
dtype: object
34.索引级别调整:df.swaplevel()
In [15]: data = pd.DataFrame(np.random.randn(18).reshape((2,9)),
    ...:     columns=[['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd', 'd'],
    ...:     [1, 2, 3, 1, 3, 1, 2, 2, 3]],index=[['s1','s2'],['x1','x2']]).T

In [16]: data
Out[16]:
           s1        s2
           x1        x2
a 1 -0.489175  1.989853
  2 -0.803715  0.516374
  3  0.275984  0.204901
b 1  0.443108 -2.054270
  3  0.773189  0.396446
c 1 -0.298805  0.809908
  2  0.143118 -0.703121
d 2 -1.865267 -0.570579
  3  0.297032 -0.144984

In [17]: data.index.names=['key1','key2']
    ...: data.columns.names=['col1','col2']

In [18]: data
Out[18]:
col1             s1        s2
col2             x1        x2
key1 key2
a    1    -0.489175  1.989853
     2    -0.803715  0.516374
     3     0.275984  0.204901
b    1     0.443108 -2.054270
     3     0.773189  0.396446
c    1    -0.298805  0.809908
     2     0.143118 -0.703121
d    2    -1.865267 -0.570579
     3     0.297032 -0.144984

In [19]: data.swaplevel('key1','key2')

Out[19]:
col1             s1        s2
col2             x1        x2
key2 key1
1    a    -0.489175  1.989853
2    a    -0.803715  0.516374
3    a     0.275984  0.204901
1    b     0.443108 -2.054270
3    b     0.773189  0.396446
1    c    -0.298805  0.809908
2    c     0.143118 -0.703121
     d    -1.865267 -0.570579
3    d     0.297032 -0.144984
35.根据级别汇总
In [20]: data
Out[20]:
col1             s1        s2
col2             x1        x2
key1 key2
a    1    -0.489175  1.989853
     2    -0.803715  0.516374
     3     0.275984  0.204901
b    1     0.443108 -2.054270
     3     0.773189  0.396446
c    1    -0.298805  0.809908
     2     0.143118 -0.703121
d    2    -1.865267 -0.570579
     3     0.297032 -0.144984

In [21]: data.sum(level='key2')
Out[21]:
col1        s1        s2
col2        x1        x2
key2
1    -0.344872  0.745490
2    -2.525864 -0.757326
3     1.346206  0.456363
36.将列转换为索引: df.set_index()

被转化为索引的列,默认会被删除,可以添加参数drop=False来保留转化为索引的列。

In [7]: frame = pd.DataFrame({'a': range(7), 'b': range(7, 0, -1),
   ...:     'c': ['one', 'one', 'one', 'two', 'two','two', 'two'],
   ...:     'd': [0, 1, 2, 0, 1, 2, 3]})

In [8]: frame
Out[8]: 
   a  b    c  d
0  0  7  one  0
1  1  6  one  1
2  2  5  one  2
3  3  4  two  0
4  4  3  two  1
5  5  2  two  2
6  6  1  two  3

In [9]: frame.set_index(['c','d'])
Out[9]: 
       a  b
c   d      
one 0  0  7
    1  1  6
    2  2  5
two 0  3  4
    1  4  3
    2  5  2
    3  6  1
37.数据合并: pd.merge()、df1.join(df2)、pd.concat()
In [1]: import pandas as pd
   ...: import numpy as np

In [2]: frame1 = pd.DataFrame({'a': range(7), 'b': range(7, 0, -1),
   ...:     'c': ['one', 'one', 'one', 'two', 'two','two', 'two'],
   ...:     'd': [0, 1, 2, 0, 1, 2, 3]})
   ...: frame2=pd.DataFrame([[1,2,3],[4,5,6]],columns=['one','two','three'],index=['a','d']).T

In [3]: frame1
Out[3]: 
   a  b    c  d
0  0  7  one  0
1  1  6  one  1
2  2  5  one  2
3  3  4  two  0
4  4  3  two  1
5  5  2  two  2
6  6  1  two  3

In [4]: frame2
Out[4]: 
       a  d
one    1  4
two    2  5
three  3  6

In [5]: f3=pd.merge(frame1,frame2,how='outer',left_on=['c'],right_index=True,suffixes=('_left','_right'))

In [6]: f3
Out[6]: 
   a_left    b      c  d_left  a_right  d_right
0     0.0  7.0    one     0.0        1        4
1     1.0  6.0    one     1.0        1        4
2     2.0  5.0    one     2.0        1        4
3     3.0  4.0    two     0.0        2        5
4     4.0  3.0    two     1.0        2        5
5     5.0  2.0    two     2.0        2        5
6     6.0  1.0    two     3.0        2        5
6     NaN  NaN  three     NaN        3        6

#添加行(数据追加)
In [9]: df1 = pd.DataFrame({'a': range(7), 'b': range(7, 0 , -1),
   ...:  'c': ['one', 'one', 'one',
   ...:  'two', 'two','two', 'two'],
   ...: 'd': [0, 1, 2, 0, 1, 2, 3]
   ...: })

   ...: df2 = pd.DataFrame([10,20,'xx1',30],index=list('abcd')).T


In [10]: df1
Out[10]:
   a  b    c  d
0  0  7  one  0
1  1  6  one  1
2  2  5  one  2
3  3  4  two  0
4  4  3  two  1
5  5  2  two  2
6  6  1  two  3

In [11]: df2
Out[11]:
    a   b    c   d
0  10  20  xx1  30

#使用append进行数据追加(添加行)
In [12]: df1.append(df2)
Out[12]:
    a   b    c   d
0   0   7  one   0
1   1   6  one   1
2   2   5  one   2
3   3   4  two   0
4   4   3  two   1
5   5   2  two   2
6   6   1  two   3
0  10  20  xx1  30

#通常情况下index并没有太大用处,使用ignore_index=True重新建立索引,方便后期数据处理。
In [13]: df1.append(df2,ignore_index=True)
Out[13]:
    a   b    c   d
0   0   7  one   0
1   1   6  one   1
2   2   5  one   2
3   3   4  two   0
4   4   3  two   1
5   5   2  two   2
6   6   1  two   3
7  10  20  xx1  30

#也可以使用concat添加列,并添加keys来区分来源表。
In [28]: pd.concat([df1,df2],keys=['df1','df2'])
Out[28]:
        a   b    c   d
df1 0   0   7  one   0
    1   1   6  one   1
    2   2   5  one   2
    3   3   4  two   0
    4   4   3  two   1
    5   5   2  two   2
    6   6   1  two   3
df2 0  10  20  xx1  30

38.数据长宽格式的转换(透视表)
#宽格式转长格式
In [73]: data=pd.DataFrame([range(10,18),[15,24,33,13,53,21,31,91],
    ...:   [1,2,3,4,1,2,2,2]],index=['val1','val2','val3 '],columns=list('abcdefgh')).T
    ...: data2=data.unstack().reset_index()
    ...: data2.columns=['item','name','value']

In [74]: data
Out[74]:
   val1  val2  val3
a    10    15     1
b    11    24     2
c    12    33     3
d    13    13     4
e    14    53     1
f    15    21     2
g    16    31     2
h    17    91     2

In [75]: data2
Out[75]:
    item name  value
0   val1    a     10
1   val1    b     11
2   val1    c     12
3   val1    d     13
4   val1    e     14
5   val1    f     15
6   val1    g     16
7   val1    h     17
8   val2    a     15
9   val2    b     24
10  val2    c     33
11  val2    d     13
12  val2    e     53
13  val2    f     21
14  val2    g     31
15  val2    h     91
16  val3    a      1
17  val3    b      2
18  val3    c      3
19  val3    d      4
20  val3    e      1
21  val3    f      2
22  val3    g      2
23  val3    h      2

In [83]: pd.melt(data)
Out[83]:
   variable  value
0      val1     10
1      val1     11
2      val1     12
3      val1     13
4      val1     14
5      val1     15
6      val1     16
7      val1     17
8      val2     15
9      val2     24
10     val2     33
11     val2     13
12     val2     53
13     val2     21
14     val2     31
15     val2     91
16     val3      1
17     val3      2
18     val3      3
19     val3      4
20     val3      1
21     val3      2
22     val3      2
23     val3      2

In [87]: data2.pivot('item','name')
Out[87]:
     value
name     a   b   c   d   e   f   g   h
item
val1    10  11  12  13  14  15  16  17
val2    15  24  33  13  53  21  31  91
val3     1   2   3   4   1   2   2   2

以上内容根据《利用Python进行数据分析·第2版》进行整理。
参考链接:https://www.jianshu.com/p/161364dd0acf

上一篇下一篇

猜你喜欢

热点阅读