[Python] How to delete rows and columns in a table (list of drop method options)

[Python] How to delete rows and columns in a table (list of drop method options)

How to delete a table element in a Pandas DataFrame. A summary of the drop method options based on actual usage.

It is complicated because there is the same processing with different descriptions, You can delete a matrix by remembering "columns = label" and "index = label".

Click here for a list of options ▶ [Drop method option list quick reference table](# 1 drop method option list quick reference table)


**table of contents**
  1. [Drop method / option list quick reference table](# 1 drop method option list quick reference table)
  2. [Delete matrix with drop method](# 2 Delete matrix with drop method)
    1. drop(label, axis)
  3. [axis = 0 (optional)](# 1-1-axis0) 2. axis='index' 3. axis=1 4. axis='columns' 2. drop(index=label) 3. drop(columns=label)
  4. [Other options for drop method](# 3 Other options for drop method)
  5. [Allow overwrite](# Allow overwrite)
  6. [Hide error](#Hide error)

## 1. 1. drop method option list quick reference table
option Description example Contents
(columns=label) df.drop(columns=['x', 'y']) Column x,Delete y
(index=label) df.drop(index=['A', 'B'] Line A,Delete B
(labe) df.drop(['A', 'B']) Line A,Delete B
(label, axis='index') df.drop(['A', 'B'], axis='index') Line A,Delete B
(label, axis=1) df.drop(['x', 'y'], axis=1) Column x,Delete y
(label, axis='columns') df.drop(['x', 'y'], axis='columns') Column x,Delete y
(errors='ignore') df.drop(['aaa'], axis='columns', errors='ignore') Ignore error
(inplace=True) df.drop(['A', 'B'], inplace=True) Overwrite

--"Df": Variable with table --"Label": row or column name --Create another object without overwriting the default --Matrix can be specified only with either "index =" and "columns =" or "axis = 1".


## Illustration ### Table to use Use the table below with 4 rows and 4 columns + matrix headings.

image.png

Table code


import pandas as pd

listA = ['AAA', 'BBB', 'CCC', 'DDD']
listB = ['EEE', 'FFF', 'GGG', 'HHH']
listC = ['III', 'JJJ', 'KKK', 'LLL']
listD = ['MMM', 'NNN', 'OOO', 'PPP']

df = pd.DataFrame(listA)
df[1] = listB
df[2] = listC
df[3] = listD

df.columns = ['aaa', 'bbb', 'ccc', 'ddd']
df.index = [111,222,333,444]

df

## 2. Drop the matrix with the drop method There are three methods to drop rows and columns with the drop method.

①drop(label, axis) ②drop(index=label) ③drop(columns=label)


①drop(label, axis) Specify the deletion target with "label" (matrix name) and axis (column name or row name).

** Basic type ** df.drop(label, axis=A) └ "df": Table data (DataFrame type) └ "drop ()": Drop method └ "label": Row / column name to delete └ "axis = A": Specify row or column with A

** ▼ Point ** --Specify either row or column with axis. --There are 4 patterns for specifying axsi. --A new DataFrame object is created with the original table intact. --Can be restored even if erased by mistake

** ▼ How to specify 4 axes **

value Description example Contents
0 axis=0(Optional) 行名で指定。デフォルト。Optional
1 axis=1 Specified by column name
index axis='index' Specified by line name
columns axis='columns' Specified by column name

Delete by line name

The following two axes (three including omissions) can be described.

① axis = 0 (optional) ②axis='index'

(1-1) axis=0 df.drop([label1,label2,,,], axis=0) df.drop([label1,label2,,,])

Even if axis = 0 is ** omitted **, the same processing will be performed.

** ▼ Specify only one column **

(axis=0) Omitted


df.drop(333)

#output

	aaa	bbb	ccc	ddd
111	AAA	EEE	III	MMM
222	BBB	FFF	JJJ	NNN
444	DDD	HHH	LLL	PPP

(axis=0) No omission


df.drop(333, axis=0)

#output

	aaa	bbb	ccc	ddd
111	AAA	EEE	III	MMM
222	BBB	FFF	JJJ	NNN
444	DDD	HHH	LLL	PPP

** ▼ Specify multiple columns **

Multiple column names


df.drop([111,333])

#output

	aaa	bbb	ccc	ddd
222	BBB	FFF	JJJ	NNN
444	DDD	HHH	LLL	PPP

(1-2) axis='index' Even if "axis ='index'" is specified, it is the same as axis = 0 (omitted).

df.drop([label1,label2,,,], axis='index')

axis='index'


df.drop([111,333], axis='index')

#output

	aaa	bbb	ccc	ddd
222	BBB	FFF	JJJ	NNN
444	DDD	HHH	LLL	PPP

### Delete by line name The following two descriptions are possible for axis.

①axis=1 ②axis='columns'

(1-3) axis=1

df.drop([label1,label2,,,], axis=1) └ “1” of axis = 1 points to the row of column name.

** ▼ Specify only one column ** In the case of one column, the same processing is performed even if there is no [].

df.drop(['AAA'], axis=1) df.drop('AAA', axis=1)

(axis=1)


df.drop('bbb', axis=1)

#output

	aaa	ccc	ddd
111	AAA	III	MMM
222	BBB	JJJ	NNN
333	CCC	KKK	OOO
444	DDD	LLL	PPP

** ▼ Specify multiple columns **

Multiple column names


df.drop(['bbb','ddd'], axis=1)

#output

	aaa	ccc
111	AAA	III
222	BBB	JJJ
333	CCC	KKK
444	DDD	LLL

(1-4) axis='columns' Even if "axis ='columns'" is specified, it becomes the same as axis = 1.

df.drop([label1,label2,,,], axis='columns')

axis='columns'


df.drop(['bbb','ddd'], axis='columns')

#output

	aaa	ccc
111	AAA	III
222	BBB	JJJ
333	CCC	KKK
444	DDD	LLL

②drop(index=label) How to delete by specifying a line name.

df.drop(index=label) └ Describe the line name you want to delete in "label".

index=label


df.drop(index=[222,444])

#output

	aaa	bbb	ccc	ddd
111	AAA	EEE	III	MMM
333	CCC	GGG	KKK	OOO

The process is the same as the following three. df.drop(label) df.drop(label, axis=0) df.drop(label, axis='index')


③drop(columns=label) How to delete by specifying a column name.

df.drop(columns=label) └ "label": Describe the column name you want to delete

index=label


df.drop(columns=['ddd','bbb'])

#output

	aaa	ccc
111	AAA	III
222	BBB	JJJ
333	CCC	KKK
444	DDD	LLL

Same as the following two. df.drop(label, axis=1) df.drop(label, axis='columns')


## 3. 3. Other options for the drop method

① Allow overwriting

The default does not change the original table and creates a new object. (It can be restored even if it is deleted by mistake)

Option to turn off this feature. inplace=True └ Default is "False"

Allow overwrite


df.drop(columns=['ddd','bbb'], inplace=True)

df

#output
	aaa	ccc
111	AAA	III
222	BBB	JJJ
333	CCC	KKK
444	DDD	LLL

The original table (df) has been rewritten.


## ② Do not display the error You can optionally set ʻerrors ='ignore'` to ignore the errors. └ The default is "errors ='raise'"
** ▼ ʻerrors ='ignore'` option usage example **

Delete non-existent column


df.drop(columns=['xxx'], errors='ignore')

Nothing is displayed.

If there is no description of "errors ='ignore'", it will be displayed as follows. ⇒「KeyError: "['xxx'] not found in axis"」


[Back to top](# How to delete a matrix in a python table drop method option list)

Recommended Posts

[Python] How to delete rows and columns in a table (list of drop method options)
[Python] How to add rows and columns to a table (pandas DataFrame)
How to get a list of built-in exceptions in python
[Python] How to get & change rows / columns / values from a table.
How to delete multiple specified positions (indexes) in a Python list
How to clear tuples in a list (Python)
[Python] How to put any number of standard inputs in a list
How to format a list of dictionaries (or instances) well in Python
How to pass the execution result of a shell command in a list in Python
How to write a list / dictionary type of Python3
[Python] How to sort dict in list and instance in list
[Pandas] How to check duplicates and delete duplicates in a table (equivalent to deleting duplicates in Excel)
How to get a list of files in the same directory with python
How to identify the element with the smallest number of characters in a Python list?
[GCF + Python] How to upload Excel to GCS and create a new table in BigQuery
How to check in Python if one of the elements of a list is in another list
[Python] How to make a list of character strings character by character
How to shuffle a part of a Python list (at random.shuffle)
How to use the __call__ method in a Python class
I tried "How to get a method decorated in Python"
How to develop in a virtual environment of Python [Memo]
Comparison of how to use higher-order functions in Python 2 and 3
How to get the last (last) value in a list in Python
[Python] How to create a table from list (basic operation of table creation / change of matrix name)
How to pass the execution result of a shell command in a list in Python (non-blocking version)
How to determine the existence of a selenium element in Python
[Python] How to force a method of a subclass to do something specific
Try to get a list of breaking news threads in Python.
How to check the memory size of a variable in Python
How to check the memory size of a dictionary in Python
[Python] How to convert a 2D list to a 1D list
Display a list of alphabets in Python 3
How to get a stacktrace in python
How to display multiplication table in python
Summary of how to use Python list
How to use is and == in Python
How to send a visualization image of data created in Python to Typetalk
[Introduction to Python] How to sort the contents of a list efficiently with list sort
How to put a half-width space before letters and numbers in Python.
[Introduction to Python] How to delete rows that meet multiple conditions in Pandas.DataFrame
[Python] How to read a csv file (read_csv method of pandas module)
How to stop a program in python until a specific date and time
[Python] How to create a dictionary type list, add / change / delete elements, and extract with a for statement
How to generate permutations in Python and C ++
Summary of how to import files in Python 3
[Python] Swapping rows and columns in Numpy data
How to create a JSON file in Python
Make a copy of the list in Python
Summary of how to use MNIST in Python
How to notify a Discord channel in Python
[Python] How to draw a histogram in Matplotlib
List of Python code to move and remember
Add totals to rows and columns in pandas
How to plot autocorrelation and partial autocorrelation in python
How to remove duplicate elements in Python3 list
How to achieve something like a list of void * (or variant) in Go?
How to drop Google Docs in one folder in a .txt file with python
How to count the number of elements in Django and output to a template
How to convert / restore a string with [] in python
How to get the number of digits in Python
[Python] How to expand variables in a character string