series | 机器学习 |《python学习之路》| python 技术论坛-江南app体育官方入口

未匹配的标注

数据结构

series

简介

可以理解为是建立在numpy中array的基础上增加索引的一维数组。

使用
  • 创建series,创建series时可以传入两个参数data和index,和numpy一样data可以传列表、元祖,index也是如此,当传入字典的时候,它的键会作为index,值作为data,还可以传array
      >>> import pandas as pd
      >>> import numpy as np
      >>> pd.series([1,2,3,4],["a","b","c","d"])
      a    1
      b    2
      c    3
      d    4
      >>> pd.series((1,2,3,4),("a","b","c","d"))
      a    1
      b    2
      c    3
      d    4
      dtype: int64
      >>> pd.series({"a":1,"b":2,"c":3,"d":4})
      a    1
      b    2
      c    3
      d    4
      dtype: int64
      >>> pd.series(np.arange(4))
      0    0
      1    1
      2    2
      3    3
      dtype: int32
  • 选择数据,在选择数据的时候,series可以直接根据索引来选择,他也可以进行切片和遍历的操作
      >>> s1[0]
      0
      >>> for i in s1:
      ...     print(i)
      ...
      0
      1
      2
      3
      >>> s1[1:3]
      1    1
      2    2
      dtype: int32
    • series还可以根据条件选择数据
      >>> s1[s1>0]
      1    1
      2    2
      3    3
      dtype: int32
  • series简单的数学运算,series跟numpy里的array一样,也可以进行四则运算,不仅可以和数,也可以和series对象进行,在和series对象进行运算的时候,根据索引来操作,假如有存在空的时候会出现nan
      >>> s1 = pd.series(np.arange(4))
      >>> s15
      0    5
      1    6
      2    7
      3    8
      dtype: int32
      >>> s1-3
      0   -3
      1   -2
      2   -1
      3    0
      dtype: int32
      >>> s1*2
      0    0
      1    2
      2    4
      3    6
      dtype: int32
      >>> s1/6
      0    0.000000
      1    0.166667
      2    0.333333
      3    0.500000
      dtype: float64
      >>> s2 = pd.series(np.random.random(3))
      >>> s2
      0    0.038811
      1    0.860956
      2    0.751210
      dtype: float64
      >>> s1s2
      0    0.038811
      1    1.860956
      2    2.751210
      3         nan
      dtype: float64
      >>> s1-s2
      0   -0.038811
      1    0.139044
      2    1.248790
      3         nan
      dtype: float64
      >>> s1*s2
      0    0.000000
      1    0.860956
      2    1.502420
      3         nan
      dtype: float64
      >>> s1/s2
      0    0.000000
      1    1.161500
      2    2.662372
      3         nan
      dtype: float64
    在进行不同精度的四则运算时,pandas会让结果的精度和两个series中精度更精确的那个一样
    • 同样也可以使用add/sub等这样的方法进行操作
      >>> s1.add(s2)
      0    0.038811
      1    1.860956
      2    2.751210
      3         nan
      dtype: float64
      >>> s1.sub(s2)
      0   -0.038811
      1    0.139044
      2    1.248790
      3         nan
      dtype: float64

本文章首发在 江南app体育官方入口 网站上。

上一篇 下一篇
讨论数量: 0



暂无话题~
网站地图