美文网首页
数据分析之 pandas 模块

数据分析之 pandas 模块

作者: 王镇_ee87 | 来源:发表于2021-01-08 10:07 被阅读0次

常用的两个类 Series 一维 DataFrame 二维

Series 一种类似于数组的对象,由两部分组成:
  • values: 一组数据 (ndarray类型)
  • index: 相关的数据索引标签
Series 的创建
  • 由列表或numpy数组创建
  • 由字典创建
Series(data=[1,2,3])  # 必须是一维结构 index 默认 0,1,2

0    1
1    2
2    3
dtype: int64

s = Series(data=[1,2,3],index=['q','w','e'])  # 必须是一维结构

q    1
w    2
e    3
dtype: int64

Series 索引和切片
print(s[0])
1
print(s['q'])
1
print(s.w)
2
print(s[[1,2]]) # 访问 1 2 两个元素

w    2
e    3

# 切片

print(s[0:1])

q    1
dtype: int64

print(s['q':"w"])

q    1
w    2
dtype: int64

常用属性
print(s.shape)  # 形状
(3,)
print(s.size) # 大小
3
print(s.index) # 索引 有显示 没有默认索引
Index(['q', 'w', 'e'], dtype='object')
print(s.values)  # value值
[1 2 3]
常用的方法
# 常用的方法
print(s.head(3)) # 前几个元素
0    1
1    2
2    3
dtype: int64

print(s.tail(3)) # 后几个元素

0    1
1    2
2    3
dtype: int64

s1 = Series(data=[1,1,2,2,3,3,4])
print(s1.unique()) # 元素去重

[1 2 3 4]

print(s1.nunique()) # 元素去重后的个数
4
print(s1.isnull()) # 检测元素是否为空
0    False
1    False
2    False
3    False
4    False
5    False
6    False
dtype: bool
print(s1.notnull()) # 检测元素是否为非空
0    True
1    True
2    True
3    True
4    True
5    True
6    True
dtype: bool
算术运算
s = Series(data=[1,2,3],index=['a','b','c'])
s1 = Series(data=[1,2,3],index=['a','d','c'])
s2 = s+s1

a    2.0
b    NaN
c    6.0
d    NaN
dtype: float64
DataFrame 是一个【表格型】的数据结构,DataFrame由按照一定顺序排列的多列数据组成。设计初衷就是将Series的使用场景从一维拓展到多维。DataFrame既有行索引,也有列索引。

-行索引:index
-列索引: columns

  • 值: values
创建

ret = DataFrame(data=[[1, 2, 3], [4, 5, 6]])

   0  1  2
0  1  2  3
1  4  5  6

dic = {"name": ["wz", "tp", "qq"], "salary": [100, 200, 300]}

ret1 = DataFrame(data=dic)


  name  salary
0   wz     100
1   tp     200
2   qq     300

DataFrame(data=(np.ones(shape=(3, 2))), index=['a', 'b', 'c'], columns=["A", "B"])

     A    B
a  1.0  1.0
b  1.0  1.0
c  1.0  1.0

DataFrame 常用的属性

ret= DataFrame(data=(np.ones(shape=(3, 2))), index=['a', 'b', 'c'], columns=["A", "B"])

print(ret.shape)   # 形状
(3, 2)

print(ret.values) # 元素值
[[1. 1.]
 [1. 1.]
 [1. 1.]]

print(ret.index)  # 行索引
Index(['a', 'b', 'c'], dtype='object')

print(ret.columns)  # 列索引
Index(['A', 'B'], dtype='object')

索引取值
  • iloc 通过隐式索引取行
  • loc 通过显示索引取行
    A   B   C   D
a  27   4  91  80
b   9  64  14  10
c  89  19  58  60
d   9  45  32  93
e  66  41   5  34
Name: A, dtype: int64

print(ret['A'])  # == ret.A 显示索引取列
a    27
b     9
c    89
d     9
e    66
Name: A, dtype: int64

print(ret.iloc[:, 0])  # 隐示索引取列
a    27
b     9
c    89
d     9
e    66
Name: A, dtype: int64
# 取行
print(ret.loc['a'])  # 显示索引取行
A    27
B     4
C    91
D    80
Name: a, dtype: int64

print(ret.iloc[0])  # 隐示索引取行
A    27
B     4
C    91
D    80
Name: a, dtype: int64

# 取元素

print(ret.loc["b","B"])   # 显示索引取元素
64
print(ret.iloc[1,1])   # 隐式索引取元素
64
print(ret.iloc[[1,2],1]) # 取 第一二行的第一列 从0 开始

b    64
c    19
Name: B, dtype: int64

切片
    A   B   C   D
a  42  35  57  56
b  80  42  85  49
c  97  97  59  12
d  20  30  24  28
e  26  27  42  28

print(ret.iloc[:, 0:2])  # 通过隐式索引 取列
    A   B
a  42  35
b  80  42
c  97  97
d  20  30
e  26  27

print(ret.loc[:, "A":"B"])  # 通过显示式索引 取列
    A   B
a  42  35
b  80  42
c  97  97
d  20  30
e  26  27

print(ret[0:2])  # 取前两行

    A   B   C   D
a  42  35  57  56
b  80  42  85  49

切片索引总结

索引

  • ret[col] 取列
  • ret.loc[index] 取行
  • ret.iloc[:,col1,col3] 取列
    切片
  • ret[index1:index3] 切行
  • ret.iloc[:,col1:col3] 切列
处理空值 之 删除所在行
ret = DataFrame(data=(np.random.randint(0, 100, size=(5, 4))), index=['a', 'b', 'c', 'd', 'e'],
                columns=["A", "B", "C", "D"])

    A   B   C   D
a  76  27  24  52
b   5  99  95  26
c  35  33   4  57
d  45  81  47  88
e  92  43  21  79
# 手动置空数据
ret.iloc[2, 3] = None
ret.iloc[4, 1] = None
ret.iloc[1, 2] = None

    A     B     C     D
a  76  27.0  24.0  52.0
b   5  99.0   NaN  26.0
c  35  33.0   4.0   NaN
d  45  81.0  47.0  88.0
e  92   NaN  21.0  79.0

# 将空值行 删除
# isnull notnull 检测元素是否为空值  notnull + all连用 isnull + any 连用
# any all 检测行列中是否有空值 axis = 0 列 axis = 1 行
index= ret.notnull().all(axis=1) # 把True False 当做行索引
ret.loc[index]

    A     B     C     D
a  76  27.0  24.0  52.0
d  45  81.0  47.0  88.0

# isnull notnull 检测元素是否为空值  notnull+ all连用  isnull + any 连用
index= ret.isnull().any(axis=1) # 把True False 当做行索引
print(ret.loc[-index]) # 索引取反 结果相同
print(ret.loc[~index]) # 取反 减号和波浪线都可以取反

    A     B     C     D
a  76  27.0  24.0  52.0
d  45  81.0  47.0  88.0

# drop开头函数 行 和列 和以前不同
ret1 = ret.dropna(axis=1) # 删除列

    A
a  80
b  69
c  34
d  75
e  55

ret2 = ret.dropna(axis=0) # 删除行

    A     B     C     D
a  80  13.0  56.0  25.0
d  75  20.0   0.0  68.0

处理空值 之 填充空值

# 将空值 赋值
print(ret.fillna(value=0))  # 把空按照指定数据填充

    A     B     C     D
a  46  38.0  56.0  89.0
b  60  70.0   NaN   7.0
c  66  43.0  49.0   NaN
d   9  65.0  27.0  91.0
e  66   NaN  42.0  87.0

(ret.fillna(method="bfill",axis=1)  #  列向上填充  行向左填充 1 是行

      A     B     C     D
a  38.0  52.0  59.0  52.0
b   7.0  58.0  20.0  20.0
c  63.0  99.0  81.0   NaN
d   4.0  71.0   1.0  49.0
e  33.0  24.0  24.0  36.0

print(ret.fillna(method="ffill", axis=1))  # 列向下填充   行向右填充 0 是列

      A     B     C     D
a  46.0  38.0  56.0  89.0
b  60.0  70.0  70.0   7.0
c  66.0  43.0  49.0  49.0
d   9.0  65.0  27.0  91.0
e  66.0  66.0  42.0  87.0

处理重复的行数据
ret.iloc[1]=[6,6,6,6]
ret.iloc[3]=[6,6,6,6]
ret.iloc[4]=[6,6,6,6]

    A   B   C   D
a  94   8  63  16
b   6   6   6   6
c  62  99  25  48
d   6   6   6   6
e   6   6   6   6

# print(ret.drop_duplicates(keep="first"))  # 保留第一行
    A   B   C   D
a  94   8  63  16
b   6   6   6   6
c  62  99  25  48

# print(ret.drop_duplicates(keep="last"))  # 保留最后一行
处理异常数据
# 去除两倍方差的c列数据 超过两倍方差视为异常数据
ret = DataFrame(data=(np.random.random(size=(100, 3))), columns=['a', 'b', 'c'])
twice_std = ret['c'].std()*2

0.5856121546838708

print(ret.loc[-(ret['c']>twice_std)])
           a         b         c
0   0.098410  0.980701  0.229913
1   0.708112  0.053732  0.088544
3   0.426246  0.397871  0.458650
4   0.755058  0.883988  0.363447
5   0.821865  0.757735  0.345691
6   0.933166  0.553347  0.003675
7   0.861295  0.944037  0.205257
8   0.123134  0.064870  0.290891
9   0.961845  0.161606  0.040938
10  0.504057  0.900849  0.151937
13  0.598321  0.458578  0.446986
14  0.668289  0.001346  0.526895
15  0.851928  0.787721  0.029239
......
89  0.929992  0.881826  0.538839
90  0.392941  0.415403  0.339590
91  0.605760  0.114224  0.577329
92  0.145157  0.638680  0.211028
94  0.667892  0.608546  0.305324
95  0.807824  0.104220  0.049012
96  0.212302  0.287099  0.058159
98  0.085008  0.625935  0.082952
99  0.970903  0.255317  0.171248

级联操作
from pandas import Series, DataFrame
import pandas as pd

ret = DataFrame(data=np.random.randint(0, 100, size=(4, 3)), columns=["a", "b", "c"])

    a   b   c
0  68  43  64
1  97  23  56
2  40  45  17
3   2  96  25

ret1 = DataFrame(data=np.random.randint(0, 100, size=(4, 3)), columns=["a", "b", "c"])

    a   b   c
0  59  76   7
1  28  83  76
2   7  98  97
3   4  15  46

# 匹配级联
rr = pd.concat((ret,ret1),axis=1) # axis=1 横向 axis=0 纵向
    a   b   c   a   b   c
0  68  43  64  59  76   7
1  97  23  56  28  83  76
2  40  45  17   7  98  97
3   2  96  25   4  15  46

#不匹配级联
ret = DataFrame(data=np.random.randint(0, 100, size=(4, 3)), columns=["a", "b", "c"])
    a   b   c
0  49   8  22
1  99  36  54
2  74   9  84
3  88  32  73

ret1 = DataFrame(data=np.random.randint(0, 100, size=(4, 3)), columns=["a", "d", "c"])

    a   d   c
0  68  90  25
1  22  94  16
2   3  96  47
3  25  84  62
# 匹配级联
# rr = pd.concat((ret, ret1), axis=0,join="inner")  # axis=1 横向 axis=0 纵向 inner 不匹配的删除
    a   c
0  42  21
1   3  88
2  40  78
3   1  98
0  66  73
1  11  53
2   0  76
3  58  79

rr = pd.concat((ret, ret1), axis=0,join="outer")  # axis=1 横向 axis=0 纵向  outer 保留不匹配的
    a     b   c     d
0  49   8.0  22   NaN
1  99  36.0  54   NaN
2  74   9.0  84   NaN
3  88  32.0  73   NaN
0  68   NaN  25  90.0
1  22   NaN  16  94.0
2   3   NaN  47  96.0
3  25   NaN  62  84.0

ll = ret.append(ret1)  # 只能列与列级联 不能进行行级联 一般很少用

ret

  employee group
0       wz   AAA
1       tp   EEE
2       qq   FFF

  employee hire_date

ret1

0       wz       111
1       tp       222
2       qq       333

  employee group hire_date
0       wz   AAA       NaN
1       tp   EEE       NaN
2       qq   FFF       NaN
0       wz   NaN       111
1       tp   NaN       222
2       qq   NaN       333

合并操作

dic = {"employee": ["wz", "tp", 'qq'], "group": ["AAA", "EEE", "FFF"]}
dic1 = {"employee": ["wz", "tp", 'qq'], "hire_date": ["111", "222", "333"]}

ret = DataFrame(data=dic)

  employee group
0       wz   AAA
1       tp   EEE
2       qq   FFF

ret1 = DataFrame(data=dic1)

  employee hire_date
0       wz       111
1       tp       222
2       qq       333

pd.merge(ret,ret1,on="employee")  # 只能合并两张表 on=""合并条件 不写on 默认按两张表共有的列合并

  employee group hire_date
0       wz   AAA       111
1       tp   EEE       222
2       qq   FFF       333

dic = {"employee": ["wz", "tp"], "group": ["AAA", "EEE"], "hire_data1": [2004, 2006]}
dic1 = {"employee": ["wz", "tp", 'qq', "tp"], "hire_date": ["111", "222", "333", "444"]}
ret = DataFrame(data=dic)
  employee group  hire_data1
0       wz   AAA        2004
1       tp   EEE        2006

ret1 = DataFrame(data=dic1)

  employee hire_date
0       wz       111
1       tp       222
2       qq       333
3       tp       444

ll = pd.merge(ret, ret1, how="outer")  # outer 保留差异项 不写默认是 inner

  employee group  hire_data1 hire_date
0       wz   AAA      2004.0       111
1       tp   EEE      2006.0       222
2       tp   EEE      2006.0       444
3       qq   NaN         NaN       333

ll = pd.merge(ret, ret1)  # 默认  how="inner"
  employee group  hire_data1 hire_date
0       wz   AAA        2004       111
1       tp   EEE        2006       222
2       tp   EEE        2006       444

ll = pd.merge(ret, ret1, how="right") # 保留右表数据


  employee group  hire_data1 hire_date
0       wz   AAA      2004.0       111
1       tp   EEE      2006.0       222
2       tp   EEE      2006.0       444
3       qq   NaN         NaN       333’

ll = pd.merge(ret, ret1, how="left")  # 保留左表数据

  employee group  hire_data1 hire_date
0       wz   AAA        2004       111
1       tp   EEE        2006       222
2       tp   EEE        2006       444

dic = {"name": ["wz", "tp", "sb"], "group": ["AAA", "EEE", "eee"], "hire_data1": [2004, 2006, 2020]}
dic1 = {"employee": ["wz", "tp", 'qq', "tp"], "hire_date": ["111", "222", "333", "444"]}
ret = DataFrame(data=dic)

  name group  hire_data1
0   wz   AAA        2004
1   tp   EEE        2006
2   sb   eee        2020

ret1 = DataFrame(data=dic1)

  employee hire_date
0       wz       111
1       tp       222
2       qq       333
3       tp       444

ll = pd.merge(ret, ret1, left_on="name",right_on="employee",how="outer")  # 列名不同 需要指定左右表的合并条件

  name group  hire_data1 employee hire_date
0   wz   AAA      2004.0       wz       111
1   tp   EEE      2006.0       tp       222
2   tp   EEE      2006.0       tp       444
3   sb   eee      2020.0      NaN       NaN
4  NaN   NaN         NaN       qq       333

相关文章

网友评论

      本文标题:数据分析之 pandas 模块

      本文链接:https://www.haomeiwen.com/subject/eiobwktx.html