簡體   English   中英

在 python 中創建新的數據框列和填充值的有效方法是什么?

[英]What is an efficient way to create new dataframe column and populate values in python?

我有一對列"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

我們可以做的

model_year['out'] = model_year.agg(tuple,1).map(calculate_price)

嘗試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 元組。

這應該有效

 df['price'] = df.apply(lambda x: price((x['car_model'],x['year'])))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM