📜  pandas where - Python (1)

📅  最后修改于: 2023-12-03 15:33:23.903000             🧑  作者: Mango

Pandas Where - Python

Pandas Where is a powerful method in Pandas library which helps to modify the values based on the condition without changing the original DataFrame.

Syntax
pandas.DataFrame.where(cond, other=nan, inplace=False, axis=None,
                        level=None, errors='raise', try_cast=False)
Parameters
  1. cond: Where True, copy, otherwise use values of other.
  2. other: Where False, copy, otherwise DataFrame or Series. It can be a scalar, a DataFrame or a Series.
  3. inplace: If True, modify the DataFrame in place (do not create a new object).
  4. axis: Row or column wise operation.
  5. level: Broadcast across a level, matching Index values on the passed MultiIndex level.
  6. errors: If raise then an exception is raised if the condition is not met.
  7. try_cast: Do not attempt to cast the result to the original data type.
Example
import pandas as pd
import numpy as np

df = pd.DataFrame({'A': [1, 2, 3, 4],
                   'B': [5, 6, 7, 8],
                   'C': [9, 10, 11, 12]})

cond = df['B'] < df['C']
df['D'] = np.where(cond, df['A'], df['B'])

print(df)

Output:

   A  B   C  D
0  1  5   9  5
1  2  6  10  2
2  3  7  11  3
3  4  8  12  4

In the above example, we are creating a new DataFrame df with columns 'A', 'B', and 'C'. We have created a boolean condition using the columns 'B' and 'C', which returns True if df['B'] is less than df['C']. Using this condition, we have created a new column 'D' in df such that it has the value from column 'A' if the condition is True, otherwise it has the value from column 'B'.

Conclusion

Pandas Where is a powerful method which is used for modifying values based on a condition. It is useful when we need to modify only specific values in a DataFrame. Pandas Where returns a new DataFrame without modifying the original one unless inplace=True.