Pandas常用操作


1. 删除指定行

  • new_df = df.drop(index='行索引')
  • new_df = df.drop('行索引', axis='index')
  • new_df = df.drop('行索引', axis=0)

2. 删除指定的多行

  • new_df = df.drop(index=['行索引1', '行索引2'])
  • new_df = df.drop(['行索引1', '行索引2'], axis='index')
  • new_df = df.drop(['行索引1', '行索引2'], axis=0)

3. 删除指定列

  • new_df = df.drop(columns='列名')
  • new_df = df.drop('列名', axis='columns')
  • new_df = df.drop('列名', axis=1)

4. 删除指定的多列

  • new_df = df.drop(columns=['列名1', '列名2'])
  • new_df = df.drop(['列名1', '列名2'], axis='columns')
  • new_df = df.drop(['列名1', '列名2'], axis=1)

5. 测试

5.1 初始化数据

df = pd.DataFrame({'stu_name': ['Nancy', 'Tony', 'Tim', 'Jack', 'Lucy'], 'stu_age': [17, 16, 16, 21, 19]},
                  index=['row0', 'row1', 'row2', 'row3', 'row4'])
     stu_name  stu_age
idx0    Nancy       17
idx1     Tony       16
idx2      Tim       16
idx3     Jack       21
idx4     Lucy       19

5.2 删除row2、row3

new_df = df.drop(['row2', 'row3'], axis='index')
     stu_name  stu_age
row0    Nancy       17
row1     Tony       16
row4     Lucy       19

6. drop 常用参数含义

inplace: 是否修改原Dataframe。

  • False: 返回新的Dataframe(默认)
  • True: 直接修改原Dataframe,返回None

axis: 轴,是否从 索引 中删除标签。 (与summean等计算函数中的axis的含义不同)

  • 0index: 方向为行,默认值0
  • 1columns: 方向为列



尊重写作权利,转载请注明出处 ^_^
原文地址:https://www.cnblogs.com/convict/p/14708455.html