[pandas] 2. Access to Series elements

Table of contents

1. Access by index number (position)

2. Access by index name

3. Access by condition (conditional expression)

import numpy as np
import pandas as pd
s=pd.Series({'考号':'10182156','姓名':'王小丫','科目一':'97','科目二':'85'})

print(s)
>>> 考号     10182156
    姓名          王小丫
    科目一          97
    科目二          85
    dtype: object

1. Access by index number (position)

  • get the value of a single element
#获取第一个元素和最后一个元素
#结果中不显示索引名
print('单一索引号访问:\n',s[0],s[-1])

>>> 单一索引号访问:
     10182156 85
  • Discrete, slice to get the index name and the value of the Series

When the index number is slice indexed, it is a left-closed right-open interval

#离散、切片获取的批量数据组成Series类型
#得到索引名以及值组成的Series
print('离散列表为索引号访问1:\n',s[[0,2]],sep='')
>>> 离散列表为索引号访问:
    考号     10182156
    科目一          97
    dtype: object

print('切片索引号访问:\n',s[1:3],sep='')
>>> 切片索引号访问:
    姓名     王小丫
    科目一     97
    dtype: object

2. Access by index name

  • get the value of a single element
print('单一索引名访问:\n',s['姓名'],sep='')
>>> 单一索引名访问:
    王小丫
  • Get the Series consisting of index names and values

When the index name slices the index, both left and right are closed intervals

#切片头尾均可取到
print('离散列表为索引名访问2:\n',s[['姓名','科目二']],sep='')
>>> 离散列表为索引名访问:
    姓名     王小丫
    科目二     85
    dtype: object

print('索引名切片访问:\n',s['考号':'科目一'],sep='')
>>> 索引名切片访问:
    考号     10182156
    姓名          王小丫
    科目一          97
    dtype: object

3. Access by condition (via conditional expression)

dates=pd.date_range('20190708',periods=6)
s=pd.Series([112,37,43,58,44,48],index=dates)
print(s)
>>> 2019-07-08    112
    2019-07-09     37
    2019-07-10     43
    2019-07-11     58
    2019-07-12     44
    2019-07-13     48
    Freq: D, dtype: int64

#s.values<=50与s<=50对比
print(s.values<=50)#<class 'numpy.ndarray'>
>>> [False  True  True False  True  True]
print(s<=50)
>>> 2019-07-08    False
    2019-07-09     True
    2019-07-10     True
    2019-07-11    False
    2019-07-12     True
    2019-07-13     True
    Freq: D, dtype: bool

print(s[s.values<=50])
>>> 2019-07-09    37
    2019-07-10    43
    2019-07-12    44
    2019-07-13    48
    dtype: int64

Supongo que te gusta

Origin blog.csdn.net/xucanlax/article/details/124015924
Recomendado
Clasificación