Pandas之Series

Pandas

使Python成为数据分析强大语言的原因,最重要的是DataFrameSeries

DataFrame是数据表格,如excel形式,二维:行,列

Series是一维的

import numpy as np
import pandas as pd
from pandas import Series,DataFrame

# 绘图
import matplotlib.pyplot as plt

1、Series

Series是一种类似与一维数组的对象,由下面两部分组成:

  • values:一组数据(ndarray类型)
  • index:相关的数据索引标签

1.1、Series的创建

两种创建方式:

  • 由列表或numpy数组创建(默认索引0到N-1的整数型索引)

    Series(
        ['data=None', 'index=None', 'dtype=None', 'name=None', 'copy=False', 'fastpath=False'],
    )
    
    s1 = Series(data=np.random.randint(0,150,size=10), index=list("abcdefhijk"), name="Python")
    
    a    116
    b     59
    c     91
    d    130
    e     19
    f    147
    h    126
    i     85
    j      3
    k     43
    Name: Python, dtype: int32
    

    特别的,由ndarray创建的是引用,而不是副本,对Series元素改变也会改变原来ndarray对象中的元素。(列表没有这种情况)

  • 通过字典创建

    s2 = Series({"A":144,"B":137,"C":125,"D":99})
    
    A    144
    B    137
    C    125
    D     99
    dtype: int64
    

    特别注意:Series是pandas中核心的模块

    type(s1)  # pandas.core.series.Series
    

1.2、Series的索引和切片

​ 可以使用中括号去单个索引(此时返回的是元素类型),或者中括号里一个列表取多个索引(此时返回的仍然是一个Series类型),分为显示索引和隐式索引

  • 显示

    • 使用index中的元素作为索引值(此时是闭区间)
    S2["A"]   # 144
    S2[["A","B"]]   
    # A    144
    # B    137
    # dtype: int64
    s2["A":"C"]
    # A    144
    # B    137
    # C    125
    # dtype: int64
    
    • 使用.loc[](推荐)
    s2.loc["A"]   # 等价于s2["A"]
    s2.loc[["A","B"]]  # 等价于s2[["A","B"]] 
    s2.loc["A":"C"]  # 等价于s2["A":"C"]
    
  • 隐式(使用.iloc[]

    s2.iloc[-1]   # 99 等价于s2.loc["D"]
    s2.iloc[[0,3]]  # 等价于s2.loc[["A","D"]]
    s2.iloc[0:2]   # 等价于s2.loc["A":"B"]
    

1.3、Series的基本概念

  • 可以把Series看成一个定长的有序字典

  • 可以通过shape,size,index,values等得到series的属性。

    Series中的值就是ndarray

    s2.shape   # (10,)
    s2.size    # 4
    s2.index   # Index(['A', 'B', 'C', 'D'], dtype='object')
    s2.values  # array([144, 137, 125,  99], dtype=int64) 
    
  • 可以通过head() ,tail()快速查看Series对象的样式

    s1.head()  # 默认展示前五个
    # a    116
    # b     59
    # c     91
    # d    130
    # e     19
    # Name: Python, dtype: int32
    s1.tail()  # 默认展示后五个
    # f    147
    # h    126
    # i     85
    # j      3
    # k     43
    # Name: Python, dtype: int32
    

    当索引没有对应的值时,可能出现缺失数据显示NaN(not a number)的情况。

    s2[["A","C"]] = np.NaN
    s2
    # A      NaN
    # B    137.0
    # C      NaN
    # D     99.0
    # dtype: float64
    
  • 可以使用pd.isnull()pd.notnull(),或者自带isnull(),notnull()函数检测缺失数据。

    s2.isnull()   # 筛选空数据
    # A     True
    # B    False
    # C     True
    # D    False
    # dtype: bool
    
    # 可以使用一个变量接收返回值,通过索引找出具体的空值
    i = s2.isnull()
    s2.loc[i]
    # A   NaN
    # C   NaN
    # dtype: float64
    
    # 筛选非空数据
    s2.notnull()  # 与isnull()返回的结果正好相反
    i = s2.notnull()
    # s2.loc[i]
    # B    137.0
    # D     99.0
    # dtype: float64
    
  • Series对象本身及其实例都有一个name属性。

    s2.name = "math"  # 给s2赋一个名字
    

1.4、Series运算

  • 适用于numpy的数组运算也适合于Series

    s2 + 10
    # A      NaN
    # B    147.0
    # C      NaN
    # D    109.0
    # Name: Math, dtype: float64
    s2.add(10, fill_value=0) # 有空值的时候,自动填充为0
    # A     10.0
    # B    147.0
    # C     10.0
    # D    109.0
    # Name: Math, dtype: float64
    
    • 修改数据类型

      s3 = s2.add(10,fill_value=0)
      s3.astype(np.int8)   # 修改数据类型
      # A     10
      # B   -109  
      # C     10
      # D    109
      # Name: Math, dtype: int8
      

      说明:int8的数据范围在-128—127,所以数据会溢出。

    # 求平均值,对NaN不纳入计算
    s2.mean()  # 118.0
    # 中位数
    s2.median()  # 118.0
    # 最大值
    s2.max()  # 137.0
    # 方差
    s.std()  # 26.870057685088806
    # 幂运算
    s2.pow(2)  
    # A        NaN
    # B    18769.0
    # C        NaN
    # D     9801.0
    # Name: Math, dtype: float64
    
    # 统计数值统计
    s2.value_counts()
    # 99.0     1
    # 137.0    1
    # Name: Math, dtype: int64
    
  • Series之间的运算

    • 在运算中自动对齐不同索引的数据
    • 如果索引不对应,则补NaN
    • 注意:要想保留住所有的index,则需要使用add()函数
    s2 
    # A      NaN
    # B    137.0
    # C      NaN
    # D     99.0
    # Name: Math, dtype: float64
    s3
    # A     10.0
    # B    147.0
    # C     10.0
    # D    109.0
    # Name: Math, dtype: float64
    
    s2 + s3
    # A      NaN
    # B    284.0
    # C      NaN
    # D    208.0
    # Name: Math, dtype: float64
    
    s2.add(s3,fill_value=0)
    # A     10.0
    # B    284.0
    # C     10.0
    # D    208.0
    # Name: Math, dtype: float64
    
posted @ 2020-03-17 22:32  李大鹅  阅读(175)  评论(0编辑  收藏  举报