Pandas python удалить элемент

Pandas Remove Elements From Series

Pandas Series.drop() function is used to drop/remove elements from Series in Python. It returns the Series with the specified index labels removed. In this article, I will explain how to remove elements from the Series in Pandas by using drop() and other methods with examples.

1. Quick Examples of Remove Elements From Series

If you are in hurry below are some quick examples of the remove elements from a series in python.

2. Syntax of Pandas Series.drop()

Following is the syntax of Series.drop() function.

2.1 Parameters of drop()

Following are the parameters of drop() to remove the elements from pandas Series.

  • lables – single label or list-like, Index labels to drop.
  • axis – : Redundant for application on Series.
  • index – Redundant for application on Series, but the index can be used instead of labels.
  • columns – Use ‘index’ or ‘labels’ instead.
  • level – int or level name, optional, For MultiIndex, the level for which the labels will be dropped.
  • inplace – bool, default False: If True, do operation inplace and return None.
  • errors – Default Value: ‘raise’, If ‘ignore’, suppress the error and only existing labels are removed.

2.2 Return value of drop()

The drop() returns a Series with specified index labels removed.

3. Initialize Pandas Series

Pandas Series is a one-dimensional, Index-labeled data structure available only in the Pandas library. It can store all the datatypes such as strings, integers, float, and other python objects. We can access each element in the Series with the help of corresponding default indices.

Now, let’s create pandas series using list of values.

4. Use drop() to Remove Values from Pandas Series

You can use the Pandas Series.drop() function to drop the single element by Index or multiple elements by index from the list.

5. Drop Rows by Index using Series.iloc[]

By using Series.iloc[] property we can slice which index we want to remove from the Series. The below example drops the 3rd value. For example.

6. Remove Element at Specific Index

By combining drop() function and index, we can also remove rows from the pandas series at the specified index. Here I am removing the fourth element from the series.

Читайте также:  Send http header python

7. Remove List of Rows From Pandas Series

Let’s also see how to remove multiple elements from the pandas Series by Index number. For instance, the list [1,3,5] are passed into drop() function which will remove the specified list of rows from the Series.

Alternatively, using the drop() function with help of the slicing technique we can remove the rows along with the specified intervals. For examples.

8. Complete Examples of Remove Element From Pandas Series

9. Conclusion

In this article, I have explained how to remove elements from a series by using Series.drop() , series.iloc[] , and Series.index() functions with examples.

  • Convert Pandas Series of Lists to One Series
  • Convert Series to Dictionary(Dict) in Pandas
  • Pandas Stack Two Series Vertically and Horizontally
  • Find Intersection Between Two Series in Pandas
  • How to Plot Columns of Pandas DataFrame
  • Convert Pandas DataFrame to Series
  • How to Plot the Pandas Series
  • Pandas Iterate Over Serie
  • How to replace Pandas Series?
  • How to append Pandas Series?
  • Check values are Pandas Series unique
  • How to rename Pandas Series?
  • How to get floor or ceil values of Pandas Series?
  • How to reshape the Pandas Series?

You may also like reading:

Источник

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 , 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.

Return Series with specified index labels removed.

>>> df = pd.DataFrame(np.arange(12).reshape(3, 4), . columns=['A', 'B', 'C', 'D']) >>> df A B C D 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 
>>> df.drop(['B', 'C'], axis=1) A D 0 0 3 1 4 7 2 8 11 
>>> df.drop(columns=['B', 'C']) A D 0 0 3 1 4 7 2 8 11 
>>> df.drop([0, 1]) A B C D 2 8 9 10 11 

Drop columns and/or rows of MultiIndex DataFrame

>>> midx = pd.MultiIndex(levels=[['lama', 'cow', 'falcon'], . ['speed', 'weight', 'length']], . codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], . [0, 1, 2, 0, 1, 2, 0, 1, 2]]) >>> df = pd.DataFrame(index=midx, columns=['big', 'small'], . data=[[45, 30], [200, 100], [1.5, 1], [30, 20], . [250, 150], [1.5, 0.8], [320, 250], . [1, 0.8], [0.3, 0.2]]) >>> df big small lama speed 45.0 30.0 weight 200.0 100.0 length 1.5 1.0 cow speed 30.0 20.0 weight 250.0 150.0 length 1.5 0.8 falcon speed 320.0 250.0 weight 1.0 0.8 length 0.3 0.2 

Drop a specific index combination from the MultiIndex DataFrame, i.e., drop the combination ‘falcon’ and ‘weight’ , which deletes only the corresponding row

>>> df.drop(index=('falcon', 'weight')) big small lama speed 45.0 30.0 weight 200.0 100.0 length 1.5 1.0 cow speed 30.0 20.0 weight 250.0 150.0 length 1.5 0.8 falcon speed 320.0 250.0 length 0.3 0.2 
>>> df.drop(index='cow', columns='small') big lama speed 45.0 weight 200.0 length 1.5 falcon speed 320.0 weight 1.0 length 0.3 
>>> df.drop(index='length', level=1) big small lama speed 45.0 30.0 weight 200.0 100.0 cow speed 30.0 20.0 weight 250.0 150.0 falcon speed 320.0 250.0 weight 1.0 0.8 

Источник

Читайте также:  Store and retrieve image

pandas.Series.drop#

Remove elements of a Series based on specifying the index labels. When using a multi-index, labels on different levels can be removed by specifying the level.

Parameters labels single label or list-like

Unused. Parameter needed for compatibility with DataFrame.

index single label or list-like

Redundant for application on Series, but ‘index’ can be used instead of ‘labels’.

columns single label or list-like

No change is made to the Series; use ‘index’ or ‘labels’ instead.

level int or level name, optional

For MultiIndex, level for which the labels will be removed.

inplace bool, default False

If True, do operation inplace and return None.

errors , default ‘raise’

If ‘ignore’, suppress error and only existing labels are dropped.

Series with specified index labels removed or None if inplace=True .

If none of the labels are found in the index.

Return only specified index labels of Series.

Return series without null values.

Return Series with duplicate values removed.

Drop specified labels from rows or columns.

>>> s = pd.Series(data=np.arange(3), index=['A', 'B', 'C']) >>> s A 0 B 1 C 2 dtype: int64 
>>> s.drop(labels=['B', 'C']) A 0 dtype: int64 

Drop 2nd level label in MultiIndex Series

>>> midx = pd.MultiIndex(levels=[['lama', 'cow', 'falcon'], . ['speed', 'weight', 'length']], . codes=[[0, 0, 0, 1, 1, 1, 2, 2, 2], . [0, 1, 2, 0, 1, 2, 0, 1, 2]]) >>> s = pd.Series([45, 200, 1.2, 30, 250, 1.5, 320, 1, 0.3], . index=midx) >>> s lama speed 45.0 weight 200.0 length 1.2 cow speed 30.0 weight 250.0 length 1.5 falcon speed 320.0 weight 1.0 length 0.3 dtype: float64 
>>> s.drop(labels='weight', level=1) lama speed 45.0 length 1.2 cow speed 30.0 length 1.5 falcon speed 320.0 length 0.3 dtype: float64 

Источник

Читайте также:  Chat Demo

Как из Pandas Dataframe удалить строку?

Pandas представляет нам отличные инструменты для обработки данных, в том числе для удаления той информации, которая нам не нужна. В этой статье мы рассмотрим различные способы удаления строк из Dataframe Pandas.

Как из Pandas удалить строку?

import pandas as pd
city_data = ‘Город’:[‘Москва’, ‘Казань’, ‘Владивосток’, ‘Санкт-Петербург’, ‘Калининград’],
‘Дата основания’:[‘1147’, ‘1005’, ‘1860’, ‘1703’, ‘1255’],
‘Площадь’:[‘2511’, ‘516’, ‘331’, ‘1439’, ‘223’],
‘Население’:[‘11,9’, ‘1,2’, ‘0,6’, ‘4,9’, ‘0,4’],
‘Погода’:[‘8’, ‘8’, ’17’, ‘9’, ’12’] >
city_df = pd.DataFrame(city_data)
city_df

В Pandas для удаления строк, а также столбцов используется метод drop. Его синтаксис следующий (обратите внимание, что необязательно использовать все параметры, можно только те, которые необходимы нам):

drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=’raise’), где:

  • labels – номера или названия столбцов для удаления
  • axis – значение 0, если вы хотите удалить строки, либо 1, если планируете удалять столбцы
  • index – определяет, какие строки надо удалить
  • columns – определяет, какие столбцы надо удалить
  • inplace – изменяет оригинальный Dataframe, если параметр равен True
  • errors – игнорируются ошибки, если параметр задан как ignore

Способ 1. Удаление строки в Pandas по ее индексу

Для каждой строки в Dataframe Pandas присваивает индекс, обычно это число. В нашем учебном Dataframe, к примеру, у Москвы индекс 0, а у Калининграда 4. Давайте уберем запись с Владивостоком:

Обратите внимание, что по умолчанию метод drop не изменяет исходный dataframe, если вы хотите, что бы это было сделано, добавьте параметр inplace=True

Способ 2. Удаление строки в Pandas по ее содержанию

Предположим, нам надо убрать строку с названием города «Казань», но мы не знаем его индекса и хотим ее удалить по названию. Для этого мы должны сначала изменить столбец с индексами и вместо цифровых значений задать данные из столбца «Город»:

Теперь, когда в качестве индексов у нас названия городов, мы можем выполнить поставленную перед нами задачу:

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

Способ 3. Удаление строки в Pandas по условию

При помощи метода loc мы можем удалять строки по условию, к примеру мы хотим убрать из Dataframe те города, у которых площадь меньше 1 000 км2.

Так как мы будем применять математические условия, то сначала столбец «Площадь» мы должны перевести в формат int64:

Далее при помощи метода loc мы передадим в Dataframe отфильтрованные строки, а именно те, которые удовлетворяют условию, что Площадь > 1 000 км2

Спасибо за внимание. Дочитавшим до конца – традиционный бонус, наш ноутбук по этой статье.

P.S. Рекомендую еще ознакомиться с нашей статьей «Как из Pandas удалить столбец?».

Источник

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