Python удалить строки с определенным значением

Pandas: как удалить строки, содержащие определенную строку

Вы можете использовать следующий синтаксис для удаления строк, содержащих определенную строку в кадре данных pandas:

df[df["col"].str.contains("this string")== False ]**

В этом руководстве объясняется несколько примеров использования этого синтаксиса на практике со следующим кадром данных:

import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame df team conference points 0 A East 11 1 A East 8 2 A East 10 3 B West 6 4 B West 6 5 C East 5 

Пример 1. Удаление строк, содержащих определенную строку

В следующем коде показано, как удалить все строки в DataFrame, содержащие «A» в столбце команды:

df[df["team"].str.contains("A")== False ] # team conference points #3 B West 6 #4 B West 6 #5 C East 5**

Пример 2. Удаление строк, содержащих строку в списке

В следующем коде показано, как удалить все строки в DataFrame, содержащие «A» или «B» в столбце команды:

df[df["team"].str.contains("A|B")== False] # team conference points #5 C East 5**

Пример 3. Удаление строк, содержащих неполную строку

В предыдущих примерах мы отбрасывали строки на основе строк, которые точно соответствовали одной или нескольким строкам.

Однако, если мы хотим удалить строки, содержащие неполную строку, мы можем использовать следующий синтаксис:

#identify partial string to look for discard = ["Wes"] #drop rows that contain the partial string "Wes" in the conference column df[~df.conference.str.contains('|'.join(discard))] #team conference points #0 A East 11 #1 A East 8 #2 A East 10 #5 C East 5**

Вы можете найти больше руководств по pandas на этой странице .

Источник

Как удалить строки в Pandas DataFrame на основе условия

Мы можем использовать следующий синтаксис для удаления строк в pandas DataFrame на основе условия:

Метод 1: удаление строк на основе одного условия

Метод 2: удаление строк на основе нескольких условий

df = df[(df.col1 > 8) & (df.col2 != 'A')] 

Примечание.Мы также можем использовать функцию drop() для удаления строк из DataFrame, но эта функция оказалась намного медленнее, чем простое присвоение DataFrame отфильтрованной версии самого себя.

В следующих примерах показано, как использовать этот синтаксис на практике со следующими пандами DataFrame:

import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame df team pos assists rebounds 0 A G 5 11 1 A G 7 8 2 A F 7 10 3 A F 9 6 4 B G 12 6 5 B G 9 5 6 B F 9 9 7 B F 4 12 

Метод 1: удаление строк на основе одного условия

В следующем коде показано, как удалять строки в DataFrame на основе одного условия:

#drop rows where value in 'assists' column is less than or equal to 8 df = df[df.assists > 8] #view updated DataFrame df team pos assists rebounds 3 A F 9 6 4 B G 12 6 5 B G 9 5 6 B F 9 9 

Любая строка, которая имела значение меньше или равное 8 в столбце «помощь», была удалена из DataFrame.

Читайте также:  Php die all rights

Метод 2: удаление строк на основе нескольких условий

В следующем коде показано, как удалять строки в DataFrame на основе нескольких условий:

#only keep rows where 'assists' is greater than 8 and rebounds is greater than 5 df = df[(df.assists > 8) & (df.rebounds > 5)] #view updated DataFrame df team pos assists rebounds 3 A F 9 6 4 B G 12 6 5 B G 9 5 6 B F 9 9 

Единственные строки, которые мы сохранили в DataFrame, были те, в которых значение помощи было больше 8, а значение подбора больше 5.

Обратите внимание, что мы также можем использовать | оператор для применения фильтра «или»:

#only keep rows where 'assists' is greater than 8 or rebounds is greater than 10 df = df[(df.assists > 8) | (df.rebounds > 10)] #view updated DataFrame df team pos assists rebounds 0 A G 5 11 3 A F 9 6 4 B G 12 6 5 B G 9 5 6 B F 9 9 7 B F 4 12 

Единственные строки, которые мы сохранили в DataFrame, были те, в которых значение помощи было больше 8 или значение подбора было больше 10.

Все строки, не соответствующие одному из этих условий, удалялись.

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные операции в pandas:

Источник

Pandas: как удалить строки, содержащие определенное значение

Вы можете использовать следующий синтаксис для удаления строк в кадре данных pandas, которые содержат определенное значение в определенном столбце:

#drop rows that contain specific 'value' in 'column_name' df = df[df.column_name != value ] 

Вы можете использовать следующий синтаксис для удаления строк в кадре данных pandas, которые содержат любое значение в определенном списке:

#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 #create DataFrame df = pd.DataFrame() #view DataFrame df team name rebounds 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 rebounds points 0 Mavs Dirk 11 26 2 Spurs Tim 14 22 

Пример 2. Удаление строк, содержащих значения в списке

В следующем коде показано, как удалить любые строки в DataFrame, содержащие любое значение в списке:

import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame df team name rebounds 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 rebounds points 2 Spurs Tim 14 22 

Пример 3. Удаление строк, содержащих определенные значения в нескольких столбцах

В следующем коде показано, как удалить любые строки в DataFrame, которые содержат определенное значение в одном из нескольких столбцов:

import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame df team name rebounds 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 rebounds points 2 Spurs Tim 14 22 3 Cavs Lebron 7 29 

Источник

Читайте также:  Html slider with buttons

Pandas – Delete rows based on column values

Pandas is a powerful library for manipulating tabular data in python. When working with pandas dataframes, it might happen that you require to delete rows where a column has a specific value. In this tutorial, we will look at how to delete rows based on the column values of a pandas dataframe.

How to delete specific rows in Pandas?

There are a number of ways to delete rows based on column values. You can filter out those rows or use the pandas dataframe drop() function to remove them. The following is the syntax:

📚 Discover Online Data Science Courses & Programs (Enroll for Free)

Introductory ⭐

Intermediate ⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

# Method 1 - Filter dataframe df = df[df['Col1'] == 0] # Method 2 - Using the drop() function df.drop(df.index[df['Col1'] == 0], inplace=True)

Note that in the above syntax, we want to remove all the rows from the dataframe df for which the value of the “Col1” column is 0.

Examples

Let’s look at these methods with the help of some examples. First, we will create a sample dataframe that we’ll be using to demonstrate the different methods.

import pandas as pd # dataframe of height and weight football players df = pd.DataFrame(< 'Height': [167, 175, 170, 186, 190, 188, 158, 169, 183, 180], 'Weight': [65, 70, 72, 80, 86, 94, 50, 58, 78, 85], 'Team': ['A', 'A', 'B', 'B', 'B', 'C', 'A', 'C', 'B', 'C'] >) # display the dataframe df

dataframe with height, weight, and team information of some football players

The above dataframe contains the height (in cm) and weight (in kg) data of football players from three teams – A, B, and C.

Читайте также:  Ооо нпо питон инн 7811746498

1. Filter rows based on column values

To delete rows based on column values, you can simply filter out those rows using boolean conditioning. For example, let’s remove all the players from team C in the above dataframe. That is all the rows in the dataframe df where the value of column “Team” is “C”.

# remove rows by filtering df = df[df['Team'] != 'C'] # display the dataframe df

dataframe after removing rows for team

You can see that all the rows where the value of column “Team” was “C” have been removed. Also, notice that the filtered dataframe retains the indexes from the original dataframe.

2. Drop rows using the drop() function

You can also use the pandas dataframe drop() function to delete rows based on column values. In this method, we first find the indexes of the rows we want to remove (using boolean conditioning) and then pass them to the drop() function.

For example, let’s remove the rows where the value of column “Team” is “C” using the drop() function.

# remove rows using the drop() function df.drop(df.index[df['Team'] == 'C'], inplace=True) # display the dataframe df

dataframe after removing rows for team

You can see that all the rows with “C” as the value for the column “Team” have been removed. Again, notice that the resulting dataframe retains the original indexes. If you want to reset the index, use the pandas reset_index() function.

Also, notice that the condition used in this example is df[‘Team’] == ‘C’ because we want to know the indexes of the rows to drop. In the previous example, we used the condition df[‘Team’] != ‘C’ because we wanted to know the indexes of the rows to keep post-filtering.

For more on the pandas drop() function, refer to its documentation.

With this, we come to the end of this tutorial. The code examples and results presented in this tutorial have been implemented in a Jupyter Notebook with a python (version 3.8.3) kernel having pandas version 1.0.5

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Data Science Parichay is an educational website offering easy-to-understand tutorials on topics in Data Science with the help of clear and fun examples.

Источник

Оцените статью