1. 程式人生 > 其它 >Python學習筆記:pd.drop刪除行或列

Python學習筆記:pd.drop刪除行或列

一、介紹

通過指定標籤名稱和相應的軸,或直接指定索引或列名稱,刪除行或列。

使用多索引時,可以通過指定級別來刪除不同級別上的標籤。

使用語法:

pandas.DataFrame.drop(labels=None, 
                      axis=0,
                     index=None,
                     columns=None,
                     level=None,
                     inplace=False,
                     errors='raise')

引數解釋:

-- labels 單個標籤或者標籤列表
-- axis=0 預設 刪除index
-- axis=1 指定刪除列
-- inplace=True 修改原資料
-- level 針對多重索引 指定級別
-- index 指定索引
-- columns 指定列名

二、實操

  • 刪除簡單索引
import pandas as pd
import numpy as np

# 構建測試集
df = pd.DataFrame(np.arange(12).reshape(3,4), columns=['a','b','c','d'])
'''
   a  b   c   d
0  0  1   2   3
1  4  5   6   7
2  8  9  10  11
'''

# 刪除行
df.drop(2)
df.drop([0,1])

# 刪除列
df.drop('a', axis=1)
df.drop(['b','c'], axis=1)
df.drop(columns=['b','c']) # 同上
  • 多重索引刪除資料
# 構建複合索引測試表
midx = pd.MultiIndex(levels=[['lama', 'cow', 'falcon'],
                             ['speed', 'weight', 'length']],
                     codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2],
                            [0, 1, 2, 0, 1, 2, 0, 1, 2]])
df = pd.DataFrame(index=midx, columns=['big', 'small'],
                  data=[[45, 30], [200, 100], [1.5, 1], [30, 20],
                        [250, 150], [1.5, 0.8], [320, 250],
                        [1, 0.8], [0.3, 0.2]])
df
'''
                 big  small
lama   speed    45.0   30.0
       weight  200.0  100.0
       length    1.5    1.0
cow    speed    30.0   20.0
       weight  250.0  150.0
       length    1.5    0.8
falcon speed   320.0  250.0
       weight    1.0    0.8
       length    0.3    0.2
'''

# 刪除行
df.drop(index='length', level=1)
'''
                 big  small
lama   speed    45.0   30.0
       weight  200.0  100.0
cow    speed    30.0   20.0
       weight  250.0  150.0
falcon speed   320.0  250.0
       weight    1.0    0.8
'''

# 刪除列
df.drop(index='cow', columns='big')
'''
               small
lama   speed    30.0
       weight  100.0
       length    1.0
falcon speed   250.0
       weight    0.8
       length    0.2
'''

參考連結:Python中pandas dataframe刪除一行或一列:drop函式詳解

參考連結:pandas.DataFrame.drop

參考連結:df.drop()函式刪除多行或者多列