The correct answer is B. df[‘new_column’] = np.where(…).
The np.where()
function takes three arguments: a condition, a value to return if the condition is true, and a value to return if the condition is false. In this case, the condition is a boolean expression that compares the values in two columns. If the condition is true, the value in the new_column
will be the value in the first column. If the condition is false, the value in the new_column
will be the value in the second column.
The melt()
function converts a DataFrame from a long format to a wide format. In a long format DataFrame, each row represents a single observation, and each column represents a variable. In a wide format DataFrame, each row represents a single variable, and each column represents a single observation.
The sort_values()
function sorts a DataFrame by the values in a specified column.
Here is an example of how to use the np.where()
function to create a new column based on conditional logic applied to existing columns:
“`
import pandas as pd
df = pd.DataFrame({‘A’: [1, 2, 3], ‘B’: [4, 5, 6]})
df[‘new_column’] = np.where(df[‘A’] > 2, ‘greater than 2’, ‘less than or equal to 2’)
print(df)
A B new_column
0 1 4 greater than 2
1 2 5 less than or equal to 2
2 3 6 less than or equal to 2
“`
In this example, the new_column
is created by comparing the values in the A
column to the value 2. If the value in the A
column is greater than 2, the value in the new_column
is greater than 2
. If the value in the A
column is less than or equal to 2, the value in the new_column
is less than or equal to 2
.