Python pandas where метод

Как использовать функцию where() в Pandas (с примерами)

Функцию where() можно использовать для замены определенных значений в кадре данных pandas.

Эта функция использует следующий базовый синтаксис:

Для каждого значения в pandas DataFrame, где cond имеет значение True, сохраняется исходное значение.

Для каждого значения, где cond имеет значение False, исходное значение заменяется значением, указанным другим аргументом.

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

import pandas as pd #define DataFrame df = pd.DataFrame() #view DataFrame df points assists rebounds 0 25 5 11 1 12 7 8 2 15 7 10 3 14 9 6 4 19 12 6 5 23 9 5 6 25 9 9 7 29 4 12 

Пример 1: замена значений во всем фрейме данных

В следующем коде показано, как использовать функцию where() для замены всех значений, которые не соответствуют определенному условию во всем кадре данных pandas, значением NaN.

#keep values that are greater than 7, but replace all others with NaN df.where (df>7) points assists rebounds 0 25 NaN 11.0 1 12 NaN 8.0 2 15 NaN 10.0 3 14 9.0 NaN 4 19 12.0 NaN 5 23 9.0 NaN 6 25 9.0 9.0 7 29 NaN 12.0 

Мы также можем использовать другой аргумент, чтобы заменить значения чем-то другим, кроме NaN.

#keep values that are greater than 7, but replace all others with 'low' df.where (df>7, other='low') points assists rebounds 0 25 low 11 1 12 low 8 2 15 low 10 3 14 9 low 4 19 12 low 5 23 9 low 6 25 9 9 7 29 low 12 

Пример 2: заменить значения в определенном столбце DataFrame

В следующем коде показано, как использовать функцию where() для замены всех значений, которые не соответствуют определенному условию в определенном столбце DataFrame.

#keep values greater than 15 in 'points' column, but replace others with 'low' df['points'] = df['points']. where(df['points']>15, other='low') #view DataFrame df points assists rebounds 0 25 5 11 1 low 7 8 2 low 7 10 3 low 9 6 4 19 12 6 5 23 9 5 6 25 9 9 7 29 4 12 

Полную онлайн-документацию по функции where() в pandas можно найти здесь .

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

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

Читайте также:  Java string named parameters

Источник

pandas.DataFrame.where#

Where cond is True, keep the original value. Where False, replace with corresponding value from other . If cond is callable, it is computed on the Series/DataFrame and should return boolean Series/DataFrame or array. The callable must not change input Series/DataFrame (though pandas doesn’t check it).

other scalar, Series/DataFrame, or callable

Entries where cond is False are replaced with corresponding value from other . If other is callable, it is computed on the Series/DataFrame and should return scalar or Series/DataFrame. The callable must not change input Series/DataFrame (though pandas doesn’t check it). If not specified, entries will be filled with the corresponding NULL value ( np.nan for numpy dtypes, pd.NA for extension dtypes).

inplace bool, default False

Whether to perform the operation in place on the data.

axis int, default None

Alignment axis if needed. For Series this parameter is unused and defaults to 0.

level int, default None

Alignment level if needed.

Returns : Same type as caller or None if inplace=True .

Return an object of same shape as self.

The where method is an application of the if-then idiom. For each element in the calling DataFrame, if cond is True the element is used; otherwise the corresponding element from the DataFrame other is used. If the axis of other does not align with axis of cond Series/DataFrame, the misaligned index positions will be filled with False.

The signature for DataFrame.where() differs from numpy.where() . Roughly df1.where(m, df2) is equivalent to np.where(m, df1, df2) .

For further details and examples see the where documentation in indexing .

Читайте также:  Php проверка совпадения строк

The dtype of the object takes precedence. The fill value is casted to the object’s dtype, if this can be done losslessly.

>>> s = pd.Series(range(5)) >>> s.where(s > 0) 0 NaN 1 1.0 2 2.0 3 3.0 4 4.0 dtype: float64 >>> s.mask(s > 0) 0 0.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 
>>> s = pd.Series(range(5)) >>> t = pd.Series([True, False]) >>> s.where(t, 99) 0 0 1 99 2 99 3 99 4 99 dtype: int64 >>> s.mask(t, 99) 0 99 1 1 2 99 3 99 4 99 dtype: int64 
>>> s.where(s > 1, 10) 0 10 1 10 2 2 3 3 4 4 dtype: int64 >>> s.mask(s > 1, 10) 0 0 1 1 2 10 3 10 4 10 dtype: int64 
>>> df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B']) >>> df A B 0 0 1 1 2 3 2 4 5 3 6 7 4 8 9 >>> m = df % 3 == 0 >>> df.where(m, -df) A B 0 0 -1 1 -2 3 2 -4 -5 3 6 -7 4 -8 9 >>> df.where(m, -df) == np.where(m, df, -df) A B 0 True True 1 True True 2 True True 3 True True 4 True True >>> df.where(m, -df) == df.mask(~m, -df) A B 0 True True 1 True True 2 True True 3 True True 4 True True 

Источник

pandas.Series.where#

Where cond is True, keep the original value. Where False, replace with corresponding value from other . If cond is callable, it is computed on the Series/DataFrame and should return boolean Series/DataFrame or array. The callable must not change input Series/DataFrame (though pandas doesn’t check it).

other scalar, Series/DataFrame, or callable

Entries where cond is False are replaced with corresponding value from other . If other is callable, it is computed on the Series/DataFrame and should return scalar or Series/DataFrame. The callable must not change input Series/DataFrame (though pandas doesn’t check it). If not specified, entries will be filled with the corresponding NULL value ( np.nan for numpy dtypes, pd.NA for extension dtypes).

inplace bool, default False

Whether to perform the operation in place on the data.

Читайте также:  Python concurrent futures пример

axis int, default None

Alignment axis if needed. For Series this parameter is unused and defaults to 0.

level int, default None

Alignment level if needed.

Returns Same type as caller or None if inplace=True .

Return an object of same shape as self.

The where method is an application of the if-then idiom. For each element in the calling DataFrame, if cond is True the element is used; otherwise the corresponding element from the DataFrame other is used. If the axis of other does not align with axis of cond Series/DataFrame, the misaligned index positions will be filled with False.

The signature for DataFrame.where() differs from numpy.where() . Roughly df1.where(m, df2) is equivalent to np.where(m, df1, df2) .

For further details and examples see the where documentation in indexing .

The dtype of the object takes precedence. The fill value is casted to the object’s dtype, if this can be done losslessly.

>>> s = pd.Series(range(5)) >>> s.where(s > 0) 0 NaN 1 1.0 2 2.0 3 3.0 4 4.0 dtype: float64 >>> s.mask(s > 0) 0 0.0 1 NaN 2 NaN 3 NaN 4 NaN dtype: float64 
>>> s = pd.Series(range(5)) >>> t = pd.Series([True, False]) >>> s.where(t, 99) 0 0 1 99 2 99 3 99 4 99 dtype: int64 >>> s.mask(t, 99) 0 99 1 1 2 99 3 99 4 99 dtype: int64 
>>> s.where(s > 1, 10) 0 10 1 10 2 2 3 3 4 4 dtype: int64 >>> s.mask(s > 1, 10) 0 0 1 1 2 10 3 10 4 10 dtype: int64 
>>> df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B']) >>> df A B 0 0 1 1 2 3 2 4 5 3 6 7 4 8 9 >>> m = df % 3 == 0 >>> df.where(m, -df) A B 0 0 -1 1 -2 3 2 -4 -5 3 6 -7 4 -8 9 >>> df.where(m, -df) == np.where(m, df, -df) A B 0 True True 1 True True 2 True True 3 True True 4 True True >>> df.where(m, -df) == df.mask(~m, -df) A B 0 True True 1 True True 2 True True 3 True True 4 True True 

Источник

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