Notice
Recent Posts
Recent Comments
Link
아미(아름다운미소)
np.select 본문
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)
'랭귀지 > pandas' 카테고리의 다른 글
bool 결측치 처리 (0) | 2025.02.04 |
---|---|
assign (0) | 2025.01.09 |
pandas 빈값이 아닌면 a컬럼을 _기준으로 split 하고 첫번째값 사용 (0) | 2025.01.03 |
df 에a,b,c 컬럼이 있고 df2에도 a,b,c 컬럼이 있다면 df 에는없지만 df2애는있는 a,b,c 구하기 (0) | 2025.01.03 |
pandas에서 데이타프레임의 타입이 틀린 항목찿기 (0) | 2024.12.23 |
Comments