如何在 pandas 中按索引删除行(附示例)
您可以使用以下语法按索引号从 pandas DataFrame 中删除行:
#drop first row from DataFrame df = df. drop (index= 0 )
您可以使用以下语法按索引号从 pandas DataFrame 中删除多行:
#drop first, second, and fourth row from DataFrame df = df. drop ( index=[0,1,3 ] )
如果您的 DataFrame 将字符串作为索引值,您只需将名称作为字符串传递即可删除:
df = df. drop (index=[' first ', ' second ', ' third '])
以下示例展示了实际中如何通过索引删除行。
示例1:按索引删除行
以下代码显示如何删除 pandas DataFrame 中的第二行:
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['Mavs', 'Lakers', 'Spurs', 'Cavs'], ' first ': ['Dirk', 'Kobe', 'Tim', 'Lebron'], ' last ': ['Nowitzki', 'Bryant', 'Duncan', 'James'], ' points ': [26, 31, 22, 29]}) #view DataFrame df team first last points 0 Mavs Dirk Nowitzki 26 1 Lakers Kobe Bryant 31 2 Spurs Tim Duncan 22 3 Cavs LeBron James 29 #drop second row from DataFrame df = df. drop (index= 1 ) #view resulting dataFrame df team first last points 0 Mavs Dirk Nowitzki 26 2 Spurs Tim Duncan 22 3 Cavs LeBron James 29
示例2:通过索引删除多行
以下代码显示了如何按索引删除 pandas DataFrame 中的多行:
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['Mavs', 'Lakers', 'Spurs', 'Cavs'], ' first ': ['Dirk', 'Kobe', 'Tim', 'Lebron'], ' last ': ['Nowitzki', 'Bryant', 'Duncan', 'James'], ' points ': [26, 31, 22, 29]}) #view DataFrame df team first last points 0 Mavs Dirk Nowitzki 26 1 Lakers Kobe Bryant 31 2 Spurs Tim Duncan 22 3 Cavs LeBron James 29 #drop first, second, and fourth row from DataFrame df = df. drop ( index=[0,1,3 ] ) #view resulting dataFrame df team first last points 2 Spurs Tim Duncan 22
示例 3:当索引为字符串时删除行
以下代码显示了当索引是字符串而不是数字时如何通过索引从 pandas DataFrame 中删除行:
import pandas as pd
#createDataFrame
df = pd. DataFrame ({' team ': ['Mavs', 'Lakers', 'Spurs', 'Cavs'],
' last ': ['Nowitzki', 'Bryant', 'Duncan', 'James'],
' last ': ['Nowitzki', 'Bryant', 'Duncan', 'James'],
' points ': [26, 31, 22, 29]},
index=['A', 'B', 'C', 'D'])
#view DataFrame
df
team first last points
A Mavs Dirk Nowitzki 26
B Lakers Kobe Bryant 31
C Spurs Tim Duncan 22
D Cavs Lebron James 29
#remove rows with index values 'A' and 'C'
df = df. drop (index=[' A ',' C '])
#view resulting DataFrame
df
team first last points
B Lakers Kobe Bryant 31
D Cavs Lebron James 29