Pandas:如何删除包含特定值的行
您可以使用以下语法删除 pandas DataFrame 中特定列中包含特定值的行:
#drop rows that contain specific 'value' in 'column_name' df = df[df. column_name != value ]
您可以使用以下语法删除 pandas DataFrame 中包含特定列表中的任何值的行:
#define values values = [value1, value2, value3, ...] #drop rows that contain any value in the list df = df[df. column_name . isin (values) == False ]
以下示例展示了如何在实践中使用此语法。
示例 1:删除包含特定值的行
以下代码显示如何删除列中包含特定值的所有行:
import pandas as pd
#createDataFrame
df = pd. DataFrame ({' team ': ['Mavs', 'Lakers', 'Spurs', 'Cavs'],
' name ': ['Dirk', 'Kobe', 'Tim', 'Lebron'],
' rebounds ': [11, 7, 14, 7],
' points ': [26, 31, 22, 29]})
#view DataFrame
df
team name rebound points
0 Mavs Dirk 11 26
1 Lakers Kobe 7 31
2 Spurs Tim 14 22
3 Cavs LeBron 7 29
#drop any rows that have 7 in the rebounds column
df = df[df. rebounds != 7 ]
#view resulting DataFrame
df
team name rebound points
0 Mavs Dirk 11 26
2 Spurs Tim 14 22
示例2:删除列表中包含值的行
以下代码显示如何从 DataFrame 中删除包含列表中的值的所有行:
import pandas as pd
#createDataFrame
df = pd. DataFrame ({' team ': ['Mavs', 'Lakers', 'Spurs', 'Cavs'],
' name ': ['Dirk', 'Kobe', 'Tim', 'Lebron'],
' rebounds ': [11, 7, 14, 7],
' points ': [26, 31, 22, 29]})
#view DataFrame
df
team name rebound points
0 Mavs Dirk 11 26
1 Lakers Kobe 7 31
2 Spurs Tim 14 22
3 Cavs LeBron 7 29
#define list of values
values = [7, 11]
#drop any rows that have 7 or 11 in the rebounds column
df = df[df. rebounds . isin (values) == False ]
#view resulting DataFrame
df
team name rebound points
2 Spurs Tim 14 22
示例3:删除多列中包含特定值的行
以下代码显示如何从 DataFrame 中删除在几列之一中包含特定值的行:
import pandas as pd
#createDataFrame
df = pd. DataFrame ({' team ': ['Mavs', 'Lakers', 'Spurs', 'Cavs'],
' name ': ['Dirk', 'Kobe', 'Tim', 'Lebron'],
' rebounds ': [11, 7, 14, 7],
' points ': [26, 31, 22, 29]})
#view DataFrame
df
team name rebound points
0 Mavs Dirk 11 26
1 Lakers Kobe 7 31
2 Spurs Tim 14 22
3 Cavs LeBron 7 29
#drop any rows that have 11 in the rebounds column or 31 in the points column
df = df[(df. rebounds != 11 ) & (df. points != 31 )]
#view resulting DataFrame
df
team name rebound points
2 Spurs Tim 14 22
3 Cavs LeBron 7 29