pandas索引


pandas數據框索引是其重要組成部分,類似於excel中的行列名稱,可用於篩選、彙總、合併數據。本文介紹索引生成、多級索引、索引重置、索引使用。

將索引重置成列或刪除reset_index()

官方文檔鏈接
語法: DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill=’’)
參數說明:

  • level: int, str, tuple, or list, default None。給定要重置的索引,int指定第幾級索引,str指定索引名稱(如果有),stuple或list指定多個索引(針對多級索引),None重置所有索引
  • drop: bool, default False。是否將要重置的索引插入到數據框列中
  • inplace: bool, default False。是否原地操作數據框
  • col_level: int or str, default 0。若數據框列是多級索引,將重置的行索引插入數據框後,指定其列索引等級
  • col_fill: object, default ‘’。若數據框列是多級索引,將重置的行索引插入數據框並設定其索引等級後,其餘列索引等級名稱
import numpy as np
import pandas as pd

columns = [['class1', 'class1', 'class2', 'class2', 'class2'], 
           ['name', 'age', 'name', 'age', 'height']]
index = [['white', 'white', 'white', 'blue', 'blue', 'red', 'red', 'red'],
         ['up', 'down', 'right', 'up', 'down', 'up', 'down', 'left']]
fra = pd.DataFrame(np.random.random([8, 5]), index=index, columns=columns)

fra
Out[28]: 
               class1              class2                    
                 name       age      name       age    height
white up     0.615977  0.323556  0.529403  0.854227  0.417047
      down   0.252984  0.744790  0.151405  0.275784  0.025775
      right  0.685214  0.605265  0.193832  0.416786  0.547755
blue  up     0.267246  0.219455  0.568687  0.509591  0.078756
      down   0.072221  0.034677  0.790222  0.128744  0.993082
red   up     0.234485  0.747283  0.239909  0.621189  0.242915
      down   0.462811  0.352136  0.008509  0.043840  0.796900
      left   0.148628  0.977315  0.879377  0.988451  0.612621
   
fra.reset_index(level=1, col_level=1, col_fill='test')
Out[4]: 
         test    class1              class2                    
      level_1      name       age      name       age    height
white      up  0.512819  0.976225  0.066507  0.336387  0.617752
white    down  0.000550  0.914401  0.846046  0.801646  0.181506
white   right  0.176204  0.468514  0.731324  0.218729  0.263762
blue       up  0.658551  0.791292  0.335346  0.427632  0.970375
blue     down  0.549378  0.340649  0.793492  0.993348  0.854131
red        up  0.322048  0.145388  0.394169  0.188444  0.396524
red      down  0.143161  0.711285  0.246570  0.225234  0.270444
red      left  0.204862  0.905399  0.475958  0.292878  0.861517

將某些列設置成索引set_index()

官方文檔鏈接
語法: DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)
參數說明:

  • keys: column label or list of column labels。要設置成行索引的列
  • drop: boolean, default True。是否刪除原來的列
  • append: boolean, default False。是否在現有行索引基礎上添加新索引
  • inplace: boolean, default False。是否原地操作
  • verify_integrity: boolean, default False。是否檢測新索引中的重複值

調整索引順序、刪除或新增索引、自動填充

官方文檔鏈接
語法: DataFrame.reindex(labels=None, axis=None, method=None, copy=True, level=None, fill_value=nan, limit=None, tolerance=None)
參數說明:

  • labels: 新的索引數組,如果是多級索引,則以tuple形式傳遞參數
  • axis: 指定修改的是行還是列,0行1列
  • method: 缺失值填充方式,只有索引是單調遞增或遞減時才能用
    - None(default):不填充
    - ffill:使用前一個元素填充
    - bfill:使用後一個元素填充
    - nearest:使用最近的元素填充
  • copy: bool, default True
  • level: int or name。對於多級索引,指定labels要修改的是第幾級索引
  • fill_value: scalar, default np.NaN。缺失值填充
  • limit: 向前向後填充最大個數,與method一塊使用
a = pd.Series([1, 2, 3], index=[1, 4, 6])
a
Out[40]: 
1    1
4    2
6    3
dtype: int64

a.reindex(range(7), method='ffill', limit=1, fill_value='missing')
Out[41]: 
0    missing #前邊沒有值,所以使用指定值填充
1          1
2          1
3    missing #limit限制只能向後填充一次,故索引3使用指定值填充
4          2
5          2
6          3
dtype: object
columns = [['class1', 'class1', 'class2', 'class2', 'class2'], 
           ['name', 'age', 'name', 'age', 'height']]
index = [['white', 'white', 'white', 'blue', 'blue', 'red', 'red', 'red'],
         ['up', 'down', 'right', 'up', 'down', 'up', 'down', 'left']]
fra = pd.DataFrame(np.random.random([8, 5]), index=index, columns=columns)

fra
Out[42]: 
               class1              class2                    
                 name       age      name       age    height
white up     0.099309  0.487201  0.845269  0.846761  0.048085
      down   0.368589  0.234458  0.099907  0.696038  0.949374
      right  0.599519  0.234983  0.789913  0.115055  0.112387
blue  up     0.659007  0.949184  0.876051  0.165612  0.354524
      down   0.187546  0.220492  0.031173  0.442702  0.049742
red   up     0.853771  0.741749  0.524701  0.728447  0.232286
      down   0.244801  0.751433  0.524760  0.920340  0.569083
      left   0.342613  0.909471  0.646130  0.658234  0.547701

#調整一級索引順序且刪除索引blue
fra.reindex(['red', 'white'], level=0)
Out[43]: 
               class1              class2                    
                 name       age      name       age    height
red   up     0.853771  0.741749  0.524701  0.728447  0.232286
      down   0.244801  0.751433  0.524760  0.920340  0.569083
      left   0.342613  0.909471  0.646130  0.658234  0.547701
white up     0.099309  0.487201  0.845269  0.846761  0.048085
      down   0.368589  0.234458  0.099907  0.696038  0.949374
      right  0.599519  0.234983  0.789913  0.115055  0.112387

重命名索引名稱

官方文檔
語法: DataFrame.rename(mapper=None, axis=None, copy=True, inplace=False, level=None, errors=‘ignore’)
參數說明:

  • mapper: {old1 : new1, old1 : new1, ……}
  • axis: 0行索引,1列索引
  • level: int or level name,表示要mapper對應第幾級索引
  • errors: ignore,忽略數據框沒有但是mapper中有的索引;raise,引發錯誤。

stack()列轉行,拉長數據框

適用於多級列索引,將其中某一級或幾級轉換成行。
語法: DataFrame.stack(self, level=-1, dropna=True)
參數說明:

  • level: int, str, list, default -1。指定要轉換的哪級列索引,默認最內層一級。
  • dropna: bool, default True。刪除換行後全是NaN的行。
df = pd.DataFrame([[None, 1.0], [2.0, 3.0]], index=['cat', 'dog'], columns=[['weight', 'kg'], ['height', 'm']])

df
Out[85]: 
    weight   kg
    height    m
cat    NaN  1.0
dog    2.0  3.0

df.stack(dropna=True)
Out[86]: 
             kg  weight
cat m       1.0     NaN
dog height  NaN     2.0
    m       3.0     NaN

df.stack(dropna=False)#不刪除全是NaN的行
Out[87]: 
             kg  weight
cat height  NaN     NaN
    m       1.0     NaN
dog height  NaN     2.0
    m       3.0     NaN

df.stack(level=[0, 1]) #將所有列索引都轉換成行
Out[88]: 
cat  kg      m         1.0
dog  kg      m         3.0
     weight  height    2.0
dtype: float64

unstack()行轉列,加寬數據框

語法: DataFrame.unstack(level=-1, fill_value=None)
參數說明:

  • level:int, string, or list of these, default -1 (last level)。指定要轉換的等級索引,可以指定多級,默認是最內層一級。
  • fill_value:使用指定value替換轉換產生的缺失值nan。
columns = ['a', 'b']
index = [['white', 'white', 'white', 'white', 'white', 'white', 
          'blue', 'blue', 'blue', 'blue'],
         ['up', 'up', 'down', 'right', 'right', 'right', 'up', 
          'up', 'down', 'down'],
         ['cat', 'bird', 'lion', 'cat', 'bird', 'lion', 'bird', 
          'lion', 'cat', 'lion']]
fra = pd.DataFrame(np.random.random([10, 2]), index=index, columns=columns)
fra
Out[22]: 
                         a         b
white up    cat   0.062473  0.428980
            bird  0.085264  0.720022
      down  lion  0.218122  0.295369
      right cat   0.540926  0.667320
            bird  0.842825  0.609600
            lion  0.078433  0.791531
blue  up    bird  0.860620  0.152855
            lion  0.360273  0.830142
      down  cat   0.833308  0.585177
            lion  0.048959  0.145129

fra.unstack(level=[0, 1], fill_value='missing_value')
Out[23]: 
                  a                     ...                    b               
              white                     ...                 blue               
                 up           down      ...                   up           down
bird      0.0852644  missing_value      ...             0.152855  missing_value
cat       0.0624735  missing_value      ...        missing_value       0.585177
lion  missing_value       0.218122      ...             0.830142       0.145129

[3 rows x 10 columns]

按索引層級統計數據

DataFrame.sum(self, axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs)[source]
Return the sum of the values for the requested axis.

This is equivalent to the method numpy.sum.
Parameters:
axis : {index (0), columns (1)}
Axis for the function to be applied on.

skipna : bool, default True
Exclude NA/null values when computing the result.

level : int or level name, default None
If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series.

numeric_only : bool, default None
Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.

min_count : int, default 0
The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.

New in version 0.22.0: Added with the default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty Series is 1.

**kwargs
Additional keyword arguments to be passed to the function.

發佈了8 篇原創文章 · 獲贊 0 · 訪問量 248
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章