我有一對列的"car_model"和"year"我需要提供給一個函式作為tuple,它將回傳我的價格(浮動)。
如何迭代資料幀行,將"car_model"和"year"值發送到函式并將回傳值添加到新列中"price"?
我在想:
model_year = CAR[["car_model", "year"]]
for x in model_year.to_numpy():
model_year_tuple = tuple(x)
price = calculate_price(model_year_tuple)
//how to add to the column? the line below will always use the last calculated price
CAR['price'] = price
uj5u.com熱心網友回復:
我們可以做的
model_year['out'] = model_year.agg(tuple,1).map(calculate_price)
uj5u.com熱心網友回復:
嘗試apply:
CAR['price'] = model_year.apply(lambda x: calculate_price(tuple(x)), axis=1)
或串列理解:
CAR['price'] = [calculate_price(x) for x in zip(CAR['car_model'], CAR['year'])]
也就是說,您應該嘗試重寫您的calculate_price函式,以便它接受 numpy 陣列而不是普通的 Python 元組。
uj5u.com熱心網友回復:
這應該有效
df['price'] = df.apply(lambda x: price((x['car_model'],x['year'])))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/312991.html
