是否可以在给定 2 个参数的 csv 中找到某物的名称? Python

Is it possible to find the name of something in a csv given 2 parameters? Python

假设我有一个包含 3 列的 csv 文件,'name'、'price' 和 'color'。

我怎样才能得到名称的变量,最贵的蓝色物品,最昂贵的红色物品和最昂贵的黄色物品?

非常感谢任何帮助:)

您一次检查每一项。你会检查颜色,然后你会检查你看到的那种颜色的最后最贵的价格。如果价格更高,则记录新的最大商品的价格和名称。如果它不是更大,则继续下一个项目。

import csv
with open('names.csv', newline='') as csvfile:
     data = csv.DictReader(csv file) 

largest = {}

for row in data:
    colour = row['colour'] 
    if largest.get(colour):
          if row['price'] > largest[colour]['price']:  # new largest price
                largest[colour]['price'] = row['price']
                largest[colour]['name'] = row['name']
    else:  # not seen before, make largest price
          largest[colour] = {}
          largest[colour]['price'] = row['price']
          largest[colour]['name'] = row['name'] 

我们的计划是找到我们想要的 class(例如,“蓝色”物品),然后找到最贵的(price 列中的最大值)。

让我们定义一个示例 DataFrame:

import pandas as pd

df = pd.DataFrame({
        'name': [a for a in "abcdef"],
        'price': [1.5, 3.8, 1.4, 5.9, 3.5, 1.9],
        'color': ['blue', 'red', 'yellow', 'blue', 'red', 'yellow']
    }).set_index('name')

这是我们的 DataFrame:

      price   color
name               
a       1.5    blue
b       3.8     red
c       1.4  yellow
d       5.9    blue
e       3.5     red
f       1.9  yellow

要完成第一部分(找到特定颜色的项目),我们可以使用 Pandas' query。所以下面将select个蓝色物品保存到blue_items.

blue_items = df[df.color == "blue"] # selects the df's slice in which df.color is equals to "blue".

然后我们可以得到最高价格的索引(因为我已经定义name作为索引列,它会return名字):

blue_items["price"].idxmax()

完整代码(现在考虑导入 CSV 文件):

import pandas as pd

df = pd.read_csv("filename.csv", index_col="name")

most_exp_blue = df[df.color == "blue"]["price"].idxmax()  # the most expensive blue

most_exp_red = df[df.color == "red"]["price"].idxmax()  # the most expensive red

most_exp_yellow = df[df.color == "yellow"]["price"].idxmax()  # the most expensive yellow

使用pandas。您需要按颜色筛选并按价格排序

df[df.color == 'color2'].sort_values(by='price', ascending=False).iloc[0]

这是一些示例:

d = [dict(name = 'nm1', price=100, color='color1'),
     dict(name = 'nm2', price=200, color='color2'),
     dict(name = 'nm3', price=300, color='color3'),
     dict(name = 'nm4', price=400, color='color2')]
df = pd.DataFrame.from_dict(d)

数据框示例:

    name    price   color
0   nm1     100     color1
1   nm2     200     color2
2   nm3     300     color3
3   nm4     400     

颜色2

示例: 如果你的数据是这样的:

data={"名称":['A-Blue','B-Blue','C-Blue','A-Red','B-Red','C-Red','A-Yellow','B-Yellow','C-Yellow'], “价格”:[100,200,300,200,100,300,300,300,100], "颜色":['Blue','Blue','Blue','Red','Red','Red','Yellow','Yellow','Yellow']}

然后首先使用以下命令创建 pandas 数据框:

pdf=pd.DataFrame(数据,列=['name','price','color'])

现在使用以下命令获取记录的索引:

pdf.groupby("颜色")["价格"].idxmax()

[记得在 pandas 旧版本中使用 argmax 而不是 idxmax]

现在应用 PDF[] 来获得每种颜色的最大值的完整行:

pdf.iloc[pdf.groupby("颜色")["价格"].idxmax()]

要重置索引,请将 reset_index 添加到命令中: 所以最后的答案是:

pdf.iloc[pdf.groupby("color")["price"].idxmax()].reset_index(drop=True)

最终输出:

指数名称价格颜色

0 C-蓝 300 蓝

1 C-红 300 红

2A-Yellow 300黄

(即使您有重复的更高价格 - 第一条记录将显示为 A-黄色]