Как удалить строки в Pandas DataFrame на основе условия
Мы можем использовать следующий синтаксис для удаления строк в pandas DataFrame на основе условия:
Метод 1: удаление строк на основе одного условия
Метод 2: удаление строк на основе нескольких условий
Примечание.Мы также можем использовать функцию drop() для удаления строк из DataFrame, но эта функция оказалась намного медленнее, чем простое присвоение DataFrame отфильтрованной версии самого себя.
В следующих примерах показано, как использовать этот синтаксис на практике со следующими пандами DataFrame:
Метод 1: удаление строк на основе одного условия
В следующем коде показано, как удалять строки в DataFrame на основе одного условия:
Любая строка, которая имела значение меньше или равное 8 в столбце «помощь», была удалена из DataFrame.
Метод 2: удаление строк на основе нескольких условий
В следующем коде показано, как удалять строки в DataFrame на основе нескольких условий:
Единственные строки, которые мы сохранили в DataFrame, были те, в которых значение помощи было больше 8, а значение подбора больше 5.
Обратите внимание, что мы также можем использовать | оператор для применения фильтра «или»:
Единственные строки, которые мы сохранили в DataFrame, были те, в которых значение помощи было больше 8 или значение подбора было больше 10.
Все строки, не соответствующие одному из этих условий, удалялись.
Дополнительные ресурсы
В следующих руководствах объясняется, как выполнять другие распространенные операции в pandas:
pandas.DataFrame.drop#
Remove rows or columns by specifying label names and corresponding axis, or by specifying directly index or column names. When using a multi-index, labels on different levels can be removed by specifying the level. See the user guide for more information about the now unused levels.
Parameters labels single label or list-like
Index or column labels to drop. A tuple will be used as a single label and not treated as a list-like.
Whether to drop labels from the index (0 or ‘index’) or columns (1 or ‘columns’).
index single label or list-like
Alternative to specifying axis ( labels, axis=0 is equivalent to index=labels ).
columns single label or list-like
Alternative to specifying axis ( labels, axis=1 is equivalent to columns=labels ).
level int or level name, optional
For MultiIndex, level from which the labels will be removed.
inplace bool, default False
If False, return a copy. Otherwise, do operation inplace and return None.
errors <‘ignore’, ‘raise’>, default ‘raise’
If ‘ignore’, suppress error and only existing labels are dropped.
Returns DataFrame or None
DataFrame without the removed index or column labels or None if inplace=True .
If any of the labels is not found in the selected axis.
Label-location based indexer for selection by label.
Return DataFrame with labels on given axis omitted where (all or any) data are missing.
Return DataFrame with duplicate rows removed, optionally only considering certain columns.
How to use drop() in pandas?
![]()
While processing real time data there will be many rows and columns which are not needed for the analysis, to keep the data set concise we need to drop them from data set.
Drop is one of the main functions used to cleanse data.We can drop specified labels from rows or columns by using drop(), by mentioning corresponding axis,index or column names,level when using multi index labels on different levels.
Syntax for drop function
DataFrame.drop(self, labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=’raise’)
Parameters:
Example
let us see how to use drop through an example,
The above code imports numpy and pandas libraries.
The above lines creates and prints a dataframe df with 4 columns and 3 rows arranging numbers from 0–11.The output is as follows:
How to delete all rows in a dataframe?
I want to delete all the rows in a dataframe.
The reason I want to do this is so that I can reconstruct the dataframe with an iterative loop. I want to start with a completely empty dataframe.
Alternatively, I could create an empty df from just the column / type information if that is possible
6 Answers 6
Here’s another method if you have an existing DataFrame that you’d like to empty without recreating the column information:
df_empty is a DataFrame with zero rows but with the same column structure as df