Series第三講 索引、迭代

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])

詳細(xì)介紹

先來創(chuàng)建一個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)

根據(jù)指定的key(一個行索引或列索引)來獲取數(shù)據(jù),key不存在則返回default值,類似于python的字典。

Series.get時,key為行索引,返回一個標(biāo)量或default值

DataFrame.get時,key為列索引,返回一列數(shù)據(jù)或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

根據(jù)標(biāo)簽或布爾數(shù)組定位數(shù)據(jù)

功能和使用方法與loc一樣,請看下面的loc介紹

  1. Series.iat

根據(jù)數(shù)字(坐標(biāo)系)或布爾數(shù)組定位位置

功能和使用方法與iloc一樣,請看下面的iloc介紹

  1. Series.loc

根據(jù)標(biāo)簽或布爾數(shù)組定位數(shù)據(jù)

loc[index[, column]]

index可以是單個行標(biāo)簽、也可以是包含多個行標(biāo)簽的列表、行標(biāo)簽的切片、bool數(shù)組

column可以是單個列標(biāo)簽、也可以是包含多個列標(biāo)簽的列表、列標(biāo)簽的切片、bool數(shù)組

# Series事例
# 單個行標(biāo)簽
In [13]: s['a']                                                                 
Out[13]: 1

# 多個行標(biāo)簽的列表
In [14]: s[['a', 'c']]                                                          
Out[14]: 
a    1
c    3
dtype: int64

# 行標(biāo)簽的切片
In [16]: s['a': 'c']                                                            
Out[16]: 
a    1
b    2
c    3
dtype: int64

# bool數(shù)組
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事例
# 獲取一行或多行數(shù)據(jù)
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數(shù)組
In [27]: df.loc[df.index=='sidewinder']                                         
Out[27]: 
            max_speed  shield
sidewinder          7       8

# 獲取一列或多列數(shù)據(jù)
In [30]: df.loc[:, 'shield']                                                    
Out[30]: 
cobra         2
viper         5
sidewinder    8
Name: shield, dtype: int64

# 通過行、列獲取數(shù)據(jù)
In [31]: df.loc['viper', 'shield']                                              
Out[31]: 5

注意??:loc里的切片和python的切片不一樣,python里是左閉右開(即不包含結(jié)束值),但是loc是左閉右閉。

注意??:但是在iloc里的切片就和python的切片一樣,即符合左閉右開。

  1. Series.iloc

根據(jù)數(shù)字(坐標(biāo)系)或布爾數(shù)組定位位置,使用方法和loc類似,只是這里用的是坐標(biāo)

# Series事例
# 獲取第4(位置)數(shù)據(jù) 位置從0開始
In [34]: s[3]                                                                   
Out[34]: 4

# 獲取第4、2個數(shù)據(jù)
In [35]: s[[3, 1]]                                                              
Out[35]: 
d    4
b    2
dtype: int64

# 獲取前3條數(shù)據(jù) 也可以寫成s[[0, 1, 2]] 或 s[list(range(3))]
In [37]: s[:3]                                                                  
Out[37]: 
a    1
b    2
c    3
dtype: int64

# 獲取最后一條數(shù)據(jù)
In [41]: s[-1]                                                                  
Out[41]: 4

DataFrame和iloc類似,只是使用的是坐標(biāo)軸獲取數(shù)據(jù)。

注意??:loc里的切片和python的切片不一樣,python里是左閉右開(即不包含結(jié)束值),但是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()

返回一個可迭代對象,這個對象里的元素內(nèi)容為一個元組(索引, 值)

和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返回結(jié)果一樣,都返回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)

根據(jù)索引刪除元素,返回刪除的數(shù)值。

與python里list.pop()相似。

注意??:此方法會改變原Series的數(shù)據(jù),如果是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特定級別的數(shù)據(jù),即多層次索引時篩選數(shù)據(jù)

參數(shù)介紹:

  • key:label or tuple of label 索引的標(biāo)簽。
  • axis{0 or ‘index’, 1 or ‘columns’}, default 0 默認(rèn)對行進(jìn)行選取,如果axis=1則對列進(jìn)行選取。
  • level:object, defaults to first n levels (n=1 or len(key)) 用來指定多級索引選取時,這些索引的級別,可以是數(shù)字也可以是索引的name。顯示結(jié)果里的多級索引不包含level指定的層,因為這是過濾層。(意思是我要篩選第二層索引為xxx的數(shù)據(jù),則第二層的索引級別不會在結(jié)果中顯示,除非指定drop_level=False)。
  • drop_level:bool, default True 默認(rèn)會在結(jié)果中刪除level指定層,如果設(shè)為False,則level指定層也在結(jié)果顯示,即結(jié)果和原始數(shù)據(jù)的層級數(shù)一致。
# 首先創(chuàng)建一個多層索引對象 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

# 獲取指定索引處的值 可以看到結(jié)果中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索引的數(shù)據(jù)時,loc就不能用了。下面看xs來發(fā)揮作用吧
# 可以看到 結(jié)果中class和animal層被drop了
In [79]: df.xs(('mammal', 'cat'))                                     
Out[79]: 
            num_legs  num_wings
locomotion                     
walks              4          0

# 如果只想指定cat索引,且該索引不是第一層索引,則需要加上level參數(shù)
# 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實(shí)現(xiàn)
df.loc[:, ['num_wings', 'num_legs']]
df.loc[:, 'num_wings']

繼續(xù) 堅持 ? ? ??。?!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容