2 回答
TA贡献1942条经验 获得超3个赞
如果你想简洁,你可以试试这个:
i = range(1,7)
s = [5,10,20,35,65,70]
p = [300,500,600,800,900,1000]
df = pd.DataFrame({"ID":i,"size":s,"price":p})
df
输出:
ID size price
0 1 5 300
1 2 10 500
2 3 20 600
3 4 35 800
4 5 65 900
5 6 70 1000
下一行看起来像这样:
id_chosen = [1,4,6]
(df[df.ID.isin(id_chosen)]["price"]/df[df.ID.isin(id_chosen)]["size"]).min()
输出:
14.285714285714286
要么
min_div = (df[df.ID.isin(id_chosen)]["price"]/df[df.ID.isin(id_chosen)]["size"]).min()
print("the minimum price/size is {}".format(min_div))
输出:
the minimum price/size is 14.285714285714286
这样,您就不必创建新的数据框。希望这可以帮助。
TA贡献1831条经验 获得超10个赞
我会做这样的事情:
import numpy as np
import pandas as pd
dict = {'id': [1, 2, 3, 4, 5, 6],
'size': [5, 10, 20, 35, 65, 70],
'price': [300, 500, 600, 800, 900, 1000]
}
df = pd.DataFrame(dict)
df['price/byte'] = df['price'] / df['size']
ids_wanted = [1, 4, 6]
subset = df[df['id'].isin(ids_wanted)]
sorted_values = subset.sort_values(by='price/byte', ascending = True)
print(sorted_values['price/byte'].iloc[0])
添加回答
举报