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()函数删除多行或者多列


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM