Created
September 8, 2022 14:01
-
-
Save elowy01/31fd50c8725c06be67514b29015822bf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Extracted from : https://medium.com/analytics-vidhya/pandas-how-to-change-value-based-on-condition-fc8ee38ba529 | |
import pandas as pd | |
import numpy as np | |
data = {'Stock': ['AAPL', 'IBM', 'MSFT', 'WMT'], | |
'Price': [144.8, 141.61, 304.21, 139.5], | |
'PE': [25, 21, 39, 16], | |
'TradingExchange': ['NASDAQ', 'NYSE', 'NASDAQ', 'NYSE']} | |
df = pd.DataFrame(data) | |
#print(df) | |
# Method 1. Using df.loc | |
df["Price_Category"] = "Over 150" | |
df.loc[df["Price"] < 150, "Price_Category"] = "Under 150" | |
# Method 2. Using np.where | |
df["Price_Category"] = "Over 150" | |
df['Price_Category'] = np.where(df["Price"] < 150, "Under 150", df['Price_Category']) | |
# Method 3: Using Numpy.Select to Set Values Using Multiple Conditions | |
PE_Conditions = [ | |
(df['PE'] < 20), | |
(df['PE'] >= 20) & (df['PE'] < 30), | |
(df['PE'] >= 30) | |
] | |
PE_Categories = ['Less than 20', '20-30', '30+'] | |
df['PE_Category'] = np.select(PE_Conditions, PE_Categories) | |
print(df) | |
print(df) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment