Creating a Column with If-Else-Else Conditions in Pandas
To create a new column based on an if-elif-else condition, there are two main approaches:
Non-Vectorized Approach
This approach involves defining a function that operates on rows:
def f(row):
if row['A'] == row['B']:
val = 0
elif row['A'] > row['B']:
val = 1
else:
val = -1
return val
Then, apply it to the dataframe along the rows:
df['C'] = df.apply(f, axis=1)
Vectorized Approach
The vectorized approach utilizes np.where to create the new column directly:
df['C'] = np.where(
df['A'] == df['B'], 0, np.where(
df['A'] > df['B'], 1, -1))
This approach is more efficient for large datasets.
Here's an example using the provided dataframe:
Input DataFrame
A | B |
---|---|
2 | 2 |
3 | 1 |
1 | 3 |
Output DataFrame
A | B | C |
---|---|---|
2 | 2 | 0 |
3 | 1 | 1 |
1 | 3 | -1 |
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3