use loc indexer and give value
df.loc[df['column A'] == 2, ['column B', 'column C']] = [4, 8]
output(df):
column A column B column C
0 1 NaN NaN
1 1 NaN NaN
2 1 NaN NaN
3 2 4.0 8.0
4 2 4.0 8.0
5 2 4.0 8.0
6 3 NaN NaN
7 3 NaN NaN
8 3 NaN NaN
Answer from Panda Kim on Stack Overflow Top answer 1 of 4
4
use loc indexer and give value
df.loc[df['column A'] == 2, ['column B', 'column C']] = [4, 8]
output(df):
column A column B column C
0 1 NaN NaN
1 1 NaN NaN
2 1 NaN NaN
3 2 4.0 8.0
4 2 4.0 8.0
5 2 4.0 8.0
6 3 NaN NaN
7 3 NaN NaN
8 3 NaN NaN
2 of 4
1
Maybe you can loop outside np.where:
df["column B"], df["column C"] = [np.where( df["column A"] == 2 ,true_val,'NaN') for true_val in ['4','8']]
print(df)
# column A column B column C
# 0 1 NaN NaN
# 1 1 NaN NaN
# 2 1 NaN NaN
# 3 2 4 8
# 4 2 4 8
# 5 2 4 8
# 6 3 NaN NaN
# 7 3 NaN NaN
# 8 3 NaN NaN
29:58
np.where to derive new columns in Pandas Python datafame based ...
05:19
How to Use where() in Numpy and Pandas (Python) - YouTube
Combine multiple column ranges in pandas using numpy's np.r_
06:23
How to Convert a Pandas Dataframe to a Numpy Array - YouTube
Python Guides
pythonguides.com › python-numpy-where
Optimizing Data Analysis in Pandas Using np.where() in 2025
May 16, 2025 - In this example, I’ve used np.where() to create a new column called ‘Performance’ that labels each state as either ‘High’ or ‘Regular’ based on their sales figures. Check out Replace Values in NumPy Array by Index in Python · Sometimes you need more than just a binary True/False condition. Here’s how to handle multiple conditions: import pandas as pd import numpy as np # Sample DataFrame of US cities and temperatures data = { 'City': ['Phoenix', 'Chicago', 'Miami', 'Seattle', 'Denver'], 'Temp_F': [105, 45, 85, 60, 75] } df = pd.DataFrame(data) # First condition df['Weather'] = np.where(df['Temp_F'] > 90, 'Hot', np.where(df['Temp_F'] < 50, 'Cold', 'Moderate')) print(df)
Pandas
pandas.pydata.org › docs › reference › api › pandas.DataFrame.where.html
pandas.DataFrame.where — pandas 3.0.6 documentation
>>> 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
IncludeHelp
includehelp.com › python › numpy-where-function-multiple-conditions.aspx
Python - NumPy 'where' function multiple conditions
We will then make a new column by traversing all the percentages and giving them their corresponding divisions according to the condition. To tackle the problem of comparing two conditions only, we check the value with np.where() condition to check all the three conditions and assign the values to them. ... # Importing pandas package import pandas as pd # Import numpy package import numpy as np # Creating a Dictionary d = {'Percentage':[45,56,78,98,76,88,76,43,54,67,54,77,67,98,59]} # Creating a DataFrame df = pd.DataFrame(d) # Display Original DataFrame print("Created DataFrame 1:\n",df,"\n")
Top answer 1 of 9
145
Try this: Using the setup from @Maxu
col = 'consumption_energy'
conditions = [ df2[col] >= 400, (df2[col] < 400) & (df2[col]> 200), df2[col] <= 200 ]
choices = [ "high", 'medium', 'low' ]
df2["energy_class"] = np.select(conditions, choices, default=np.nan)
consumption_energy energy_class
0 459 high
1 416 high
2 186 low
3 250 medium
4 411 high
5 210 medium
6 343 medium
7 328 medium
8 208 medium
9 223 medium
2 of 9
99
You can use a ternary:
np.where(consumption_energy > 400, 'high',
(np.where(consumption_energy < 200, 'low', 'medium')))
Stack Overflow
stackoverflow.com › questions › 68825113 › pandas-np-where-or-np-select-generate-multiple-columns-in-1-line-code
python - Pandas np.where or np.select generate multiple columns in 1 line code - Stack Overflow
August 17, 2021 - condition = df['RB'].eq(46) # Some more interesting condition than True df[['RB', 'Valindex0']] = np.where( np.tile(condition.values[:, None], 2), # Make condition match DataFrame columns df[['RB', 'Valindex0']], None ) ... contract RB BeginDate ValIssueDate EndDate Valindex0 0 A00118 46 19000100 19880901 19841231 50 1 A00118 46 19850100 19880901 99999999 50 2 A00118 None 19000100 19880901 19831231 None 3 A00118 None 19840100 19880901 19841299 None · Multiple conditions can be done as well by creating a structure that is of the correct shape (like another DataFrame):
Top answer 1 of 4
34
Selection criteria uses Boolean indexing:
df['color'] = np.where(((df.A < borderE) & ((df.B - df.C) < ex)), 'r', 'b')
>>> df
A B C color
0 0 11 20 r
1 1 12 19 r
2 2 13 18 r
3 3 14 17 b
4 4 15 16 b
5 5 16 15 b
6 6 17 14 b
7 7 18 13 b
8 8 19 12 b
9 9 20 11 b
2 of 4
14
wrap the IF in a function and apply it:
def color(row):
borderE = 3.
ex = 0.
if (row.A > borderE) and( row.B - row.C < ex) :
return "somestring"
else:
return "otherstring"
df.loc[:, 'color'] = df.apply(color, axis = 1)
Yields:
A B C color
0 0 11 20 otherstring
1 1 12 19 otherstring
2 2 13 18 otherstring
3 3 14 17 otherstring
4 4 15 16 somestring
5 5 16 15 otherstring
6 6 17 14 otherstring
7 7 18 13 otherstring
8 8 19 12 otherstring
9 9 20 11 otherstring
GeeksforGeeks
geeksforgeeks.org › python › how-to-use-numpy-where-with-multiple-conditions-in-python
How to use NumPy where() with multiple conditions in Python ? - GeeksforGeeks
July 23, 2025 - Numpy where() with multiple conditions using logical OR. ... # Import NumPy library import numpy as np # Create an array using the list np_arr1 = np.array([23, 11, 45, 43, 60, 18, 33, 71, 52, 38]) print("The values of the input array :\n", np_arr1) # Create another array based on the # multiple conditions and one array new_arr1 = np.where((np_arr1)) # Print the new array print("The filtered values of the array :\n", new_arr1) # Create an array using range values np_arr2 = np.arange(40, 50) # Create another array based on the # multiple conditions and two arrays new_arr2 = np.where((np_arr1), np_arr1, np_arr2) # Print the new array print("The filtered values of the array :\n", new_arr2)
Top answer 1 of 2
6
Using pandas.loc[...]:
df.loc[~df['C'].isna(), 'A']=df.loc[~df['C'].isna(), 'C']
df.loc[~df['D'].isna(), 'B']=df.loc[~df['D'].isna(), 'D']
Using np.where(...):
import numpy as np
df[['A', 'B']]=np.where(df['C'].notna().to_numpy().reshape(-1,1), df[['C', 'D']], df[['A', 'B']])
Output:
A B C D
0 A1 B1 NaN NaN
1 1 2 1.0 2.0
2 3 4 3.0 4.0
3 A4 B4 NaN NaN
2 of 2
3
Try retrieving values to assign, namely:
import pandas as pd
data = [['A1', 'B1'], ['A2', 'B2', 1, 2], ['A3', 'B3', 3, 4], ['A4', 'B4']]
df = pd.DataFrame(data, columns=['A','B','C','D'])
df.loc[df['C'].notna(), ['A','B']] = df.loc[df['C'].notna(), ['C','D']].to_numpy()
df
A B C D
0 A1 B1 NaN NaN
1 1 2 1.0 2.0
2 3 4 3.0 4.0
3 A4 B4 NaN NaN
GeeksforGeeks
geeksforgeeks.org › filter-pandas-dataframe-with-multiple-conditions
Filter Pandas Dataframe with multiple conditions - GeeksforGeeks
August 7, 2024 - Output resolves for the given conditions and finally, we are going to show only 2 columns namely Name and JOB. Here will get all rows having Salary greater or equal to 100000 and Age < 40 and their JOB starts with ‘D’ from the data frame. We need to use NumPy. ... # import module import pandas as pd import numpy as np # assign data dataFrame = pd.DataFrame({'Name': [' RACHEL ', ' MONICA ', ' PHOEBE ', ' ROSS ', 'CHANDLER', ' JOEY '], 'Age': [30, 35, 37, 33, 34, 30], 'Salary': [100000, 93000, 88000, 120000, 94000, 95000], 'JOB': ['DESIGNER', 'CHEF', 'MASUS', 'PALENTOLOGY', 'IT', 'ARTIST']}) # filter dataframe filtered_values = np.where((dataFrame['Salary']>=100000) & (dataFrame['Age']< 40) & (dataFrame['JOB'].str.startswith('D'))) print(filtered_values) display(dataFrame.loc[filtered_values])
Pandas
pandas.pydata.org › pandas-docs › stable › user_guide › indexing.html
Indexing and selecting data — pandas 3.0.6 documentation
And you want to set a new column ... Out[231]: col1 col2 color 0 A Z green 1 B Z green 2 B X red 3 C Y red · If you have multiple conditions, you can use numpy.select() to achieve that....