랭귀지/pandas
np.select
유키공
2025. 2. 13. 12:25
import pandas as pd
import numpy as np
# 샘플 DataFrame 생성
df = pd.DataFrame({
"fruit": ["apple", "banana", "cherry", "date", "elderberry"],
"quantity": [5, 3, 7, 2, 4],
"price": [100, 50, 200, 30, 150]
})
# 조건 리스트 (여러 컬럼을 함께 비교)
condlist = [
(df["fruit"] == "apple") & (df["quantity"] > 4), # "apple"이고 quantity가 4보다 큰 경우
(df["fruit"] == "banana") | (df["price"] < 100), # "banana"이거나 price가 100보다 작은 경우
(df["price"] >= 150) # price가 150 이상인 경우
]
# 선택할 값 리스트
choicelist = [1, 2, 3]
# np.select 사용 (조건에 맞지 않는 경우 default 값은 0)
df["new_column"] = np.select(condlist, choicelist, default=0)
print(df)