美文网首页
Series第三讲 索引、迭代

Series第三讲 索引、迭代

作者: butters001 | 来源:发表于2020-09-17 17:49 被阅读0次

Series第三讲 索引、迭代

索引、迭代方法总览

  • Series.get(key[, default])
  • Series.at
  • Series.iat
  • Series.loc
  • Series.iloc
  • Series.__iter__()
  • Series.items()
  • Series.iteritems()
  • Series.keys()
  • Series.pop(item)
  • Series.item()
  • Series.xs(key[, axis, level, drop_level])

详细介绍

先来创建一个Series和一个DataFrame

In [2]: s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])                 

In [3]: s                                                                       
Out[3]: 
a    1
b    2
c    3
d    4
dtype: int64

In [4]: df = pd.DataFrame([[1, 2], [4, 5], [7, 8]], 
   ...:      index=['cobra', 'viper', 'sidewinder'], 
   ...:      columns=['max_speed', 'shield'])                                   

In [5]: df                                                                      
Out[5]: 
            max_speed  shield
cobra               1       2
viper               4       5
sidewinder          7       8
  1. Series.get(key, default=None)

根据指定的key(一个行索引或列索引)来获取数据,key不存在则返回default值,类似于python的字典。

Series.get时,key为行索引,返回一个标量或default值

DataFrame.get时,key为列索引,返回一列数据或default值

In [6]: s.get('a')                                                              
Out[6]: 1

In [7]: df.get('max_speed')                                                     
Out[7]: 
cobra         1
viper         4
sidewinder    7
Name: max_speed, dtype: int64

In [8]: df.get('max_speeda',0)                                                  
Out[8]: 0
  1. Series.at

根据标签或布尔数组定位数据

功能和使用方法与loc一样,请看下面的loc介绍

  1. Series.iat

根据数字(坐标系)或布尔数组定位位置

功能和使用方法与iloc一样,请看下面的iloc介绍

  1. Series.loc

根据标签或布尔数组定位数据

loc[index[, column]]

index可以是单个行标签、也可以是包含多个行标签的列表、行标签的切片、bool数组

column可以是单个列标签、也可以是包含多个列标签的列表、列标签的切片、bool数组

# Series事例
# 单个行标签
In [13]: s['a']                                                                 
Out[13]: 1

# 多个行标签的列表
In [14]: s[['a', 'c']]                                                          
Out[14]: 
a    1
c    3
dtype: int64

# 行标签的切片
In [16]: s['a': 'c']                                                            
Out[16]: 
a    1
b    2
c    3
dtype: int64

# bool数组
In [18]: bool_list = s>2                                             
In [19]: bool_list                                                              
Out[19]: 
a    False
b    False
c     True
d     True
dtype: bool

In [20]: s[bool_list]                                                           
Out[20]: 
c    3
d    4
dtype: int64
# DataFrame事例
# 获取一行或多行数据
In [24]: df.loc['cobra']                                                        
Out[24]: 
max_speed    1
shield       2
Name: cobra, dtype: int64

In [25]: df.loc[['cobra', 'viper']]                                             
Out[25]: 
       max_speed  shield
cobra          1       2
viper          4       5

In [26]: df.loc['cobra': 'viper']                                               
Out[26]: 
       max_speed  shield
cobra          1       2
viper          4       5

# bool数组
In [27]: df.loc[df.index=='sidewinder']                                         
Out[27]: 
            max_speed  shield
sidewinder          7       8

# 获取一列或多列数据
In [30]: df.loc[:, 'shield']                                                    
Out[30]: 
cobra         2
viper         5
sidewinder    8
Name: shield, dtype: int64

# 通过行、列获取数据
In [31]: df.loc['viper', 'shield']                                              
Out[31]: 5

注意⚠️:loc里的切片和python的切片不一样,python里是左闭右开(即不包含结束值),但是loc是左闭右闭。

注意⚠️:但是在iloc里的切片就和python的切片一样,即符合左闭右开。

  1. Series.iloc

根据数字(坐标系)或布尔数组定位位置,使用方法和loc类似,只是这里用的是坐标

# Series事例
# 获取第4(位置)数据 位置从0开始
In [34]: s[3]                                                                   
Out[34]: 4

# 获取第4、2个数据
In [35]: s[[3, 1]]                                                              
Out[35]: 
d    4
b    2
dtype: int64

# 获取前3条数据 也可以写成s[[0, 1, 2]] 或 s[list(range(3))]
In [37]: s[:3]                                                                  
Out[37]: 
a    1
b    2
c    3
dtype: int64

# 获取最后一条数据
In [41]: s[-1]                                                                  
Out[41]: 4

DataFrame和iloc类似,只是使用的是坐标轴获取数据。

注意⚠️:loc里的切片和python的切片不一样,python里是左闭右开(即不包含结束值),但是loc是左闭右闭。

注意⚠️:但是在iloc里的切片就和python的切片一样,即符合左闭右开。

  1. Series.__iter__()

返回一个迭代器

如果是Series,返回的是包含values的迭代器;

如果是DataFrame,返回的是包含列名的迭代器

In [42]: s.__iter__()                                                           
Out[42]: <map at 0x7fc3abc0b950>

In [43]: for a in s.__iter__(): 
    ...:     print(a) 
    ...:                                                                        
1
2
3
4
  1. Series.items()

返回一个可迭代对象,这个对象里的元素内容为一个元组(索引, 值)

和python字典的items()方法有些像

# 对Series
In [47]: s.items()                                                              
Out[47]: <zip at 0x7fc3ab361730>

In [48]: for item in s.items(): 
    ...:     print(item) 
    ...:                                                                        
('a', 1)
('b', 2)
('c', 3)
('d', 4)

# 对DataFrame
In [49]: for df_item in df.items(): 
    ...:     print(df_item) 
    ...:      
    ...:                                                                        
('max_speed', cobra         1
viper         4
sidewinder    7
Name: max_speed, dtype: int64)
('shield', cobra         2
viper         5
sidewinder    8
Name: shield, dtype: int64)
  1. Series.iteritems()

items()功能一样

  1. Series.keys()

返回对象的索引

如果是Series,则Series.keys()Series.index返回结果一样,都返回Series的索引;

如果是DataFrame,则df.keys()返回的是列索引,df.index返回的是行索引。

# 对于Series
In [51]: s.keys()                                                               
Out[51]: Index(['a', 'b', 'c', 'd'], dtype='object')

In [52]: s.index                                                                
Out[52]: Index(['a', 'b', 'c', 'd'], dtype='object')


# 对于DataFrame
In [55]: df.keys()                                                              
Out[55]: Index(['max_speed', 'shield'], dtype='object')

In [56]: df.index                                                               
Out[56]: Index(['cobra', 'viper', 'sidewinder'], dtype='object')
  1. Series.pop(item)

根据索引删除元素,返回删除的数值。

与python里list.pop()相似。

注意⚠️:此方法会改变原Series的数据,如果是DataFrame,则item需要指定列名

# 对于Series
In [58]: s.pop('a')                                                             
Out[58]: 1

In [59]: s                                                                      
Out[59]: 
b    2
c    3
d    4
dtype: int64

# 对于DataFrame
In [63]: df.pop('max_speed')                                                    
Out[63]: 
cobra         1
viper         4
sidewinder    7
Name: max_speed, dtype: int64

In [64]: df                                                                     
Out[64]: 
            shield
cobra            2
viper            5
sidewinder       8
  1. Series.item()

目前看来只对包含一个元素的Series管用 返回这个元素的值

注意⚠️:DataFrame没有item()方法

In [68]: pd.Series(['a']).item()                                                
Out[68]: 'a'
  1. Series.xs(key, axis=0, level=None, drop_level=True)

选择MultiIndex特定级别的数据,即多层次索引时筛选数据

参数介绍:

  • key:label or tuple of label 索引的标签。
  • axis{0 or ‘index’, 1 or ‘columns’}, default 0 默认对行进行选取,如果axis=1则对列进行选取。
  • level:object, defaults to first n levels (n=1 or len(key)) 用来指定多级索引选取时,这些索引的级别,可以是数字也可以是索引的name。显示结果里的多级索引不包含level指定的层,因为这是过滤层。(意思是我要筛选第二层索引为xxx的数据,则第二层的索引级别不会在结果中显示,除非指定drop_level=False)。
  • drop_level:bool, default True 默认会在结果中删除level指定层,如果设为False,则level指定层也在结果显示,即结果和原始数据的层级数一致。
# 首先创建一个多层索引对象 df
In [70]: d = {'num_legs': [4, 4, 2, 2], 
    ...:      'num_wings': [0, 0, 2, 2], 
    ...:      'class': ['mammal', 'mammal', 'mammal', 'bird'], 
    ...:      'animal': ['cat', 'dog', 'bat', 'penguin'], 
    ...:      'locomotion': ['walks', 'walks', 'flies', 'walks']}               

In [71]: df = pd.DataFrame(data=d) 
    ...: df = df.set_index(['class', 'animal', 'locomotion']) 
    ...: df 
    ...:                                                                        
Out[71]: 
                           num_legs  num_wings
class  animal  locomotion                     
mammal cat     walks              4          0
       dog     walks              4          0
       bat     flies              2          2
bird   penguin walks              2          2

# 可以看出此df对象有三层行索引,class、animal和locomotion

# 获取指定索引处的值 可以看到结果中class层被drop了
In [74]: df.xs('mammal')                                                        
Out[74]: 
                   num_legs  num_wings
animal locomotion                     
cat    walks              4          0
dog    walks              4          0
bat    flies              2          2

In [75]: df.loc['mammal']                                                       
Out[75]: 
                   num_legs  num_wings
animal locomotion                     
cat    walks              4          0
dog    walks              4          0
bat    flies              2          2

# 可以看出 df.xs('mammal') 和 df.loc['mammal'] 效果一样
# 但是我想获取cat索引的数据时,loc就不能用了。下面看xs来发挥作用吧
# 可以看到 结果中class和animal层被drop了
In [79]: df.xs(('mammal', 'cat'))                                     
Out[79]: 
            num_legs  num_wings
locomotion                     
walks              4          0

# 如果只想指定cat索引,且该索引不是第一层索引,则需要加上level参数
# level也可以指定为索引名 下面的代码等价于 df.xs('cat', level='animal')
In [80]: df.xs('cat', level=1)                                                  
Out[80]: 
                   num_legs  num_wings
class  locomotion                     
mammal walks              4          0

# 获取多级索引的值
In [86]: df.xs(('bird', 'walks'), level=[0, 'locomotion'])                      
Out[86]: 
         num_legs  num_wings
animal                      
penguin         2          2

# 获取指定列上的值
In [88]: df.xs('num_wings', axis=1)                                             
Out[88]: 
class   animal   locomotion
mammal  cat      walks         0
        dog      walks         0
        bat      flies         2
bird    penguin  walks         2
Name: num_wings, dtype: int64


In [89]: df.xs(['num_wings', 'num_legs'], axis=1)                               
Out[89]: 
                           num_wings  num_legs
class  animal  locomotion                     
mammal cat     walks               0         4
       dog     walks               0         4
       bat     flies               2         2
bird   penguin walks               2         2

# 也可以用loc实现
df.loc[:, ['num_wings', 'num_legs']]
df.loc[:, 'num_wings']

继续 坚持 ✊ ✊ ✊!!!

相关文章

  • Series第三讲 索引、迭代

    Series第三讲 索引、迭代 索引、迭代方法总览 Series.get(key[, default]) Seri...

  • pandas series

    series是一维数组 series创建 修改Series类型 Series切片和索引 Series索引和值操作

  • pandas

    显示Series的值和索引: 自带索引的Series: 将字典转换为Series:

  • Pandas的基本功能(三)

    索引、选取与过滤 Series对象 Series对象的索引类似与NumPy数组的索引,唯一的区别是Series对象...

  • pandas层次化索引

    Series 多层次索引Series的索引是MultiIndex结构 根据最外层索引取数时,可直接通过series...

  • Pandas基本功能

    Series和DataFrame的基本操作。 重新索引reindex。Series会根据索引进行重排,如果某个索引...

  • 用Python进行数据分析 第五章 Pandas入门 Day8

    5.2.3 索引、选择与过滤 Series Series的索引obj[...]与Numpy数组索引的功能相似,只不...

  • Pandas对象

    Pandas的 Series对象是一个带索引数据构成的一维数组。 Series的索引也可以是字符串 Series的创建

  • pandasⅠ- 数据结构

    一、Series的定义 二、Series的创建 三、Series的索引和切片 四、Series的运算 五、Data...

  • pandas学习-2

    Pandas数据结构Series:索引 位置下标 / 标签索引 / 切片索引 / 布尔型索引

网友评论

      本文标题:Series第三讲 索引、迭代

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