【问题标题】:How to compare the values from a column in csv file according to key values that are duplicated using python如何根据使用python复制的键值比较csv文件中列的值
【发布时间】:2019-07-03 18:18:12
【问题描述】:

我有一个包含 2 列的 .csv 文件:

Item   Value
A   1.3
B   2.6
D   4.2
E   5.6
F   3.2
A   1.2
C   5.2
D   6.4

我想比较列 Item 中的值并找到重复项,然后我想比较列 Value 中的相应值。 在示例中,Item 中的 A 和 D 是重复的,但它们在 Value 中具有不同的值。我想清除重复项并保存 Value 中值最低的那些。

这就是我尝试过的方法,它有效,但速度慢且资源昂贵。我相信有更好的方法,我可以使用 pandas 或任何其他库来解决这个问题,所以请给我一个建议。

file="file.csv"

def items_array(file):


    with open(file,"r") as file:
        file_reader=csv.DictReader(file,delimiter=";")
        for row in file_reader:
            items.append(row["Item_title"])
    items_set=set(items)
    return(items_set)


def find_lowest_value(item,file):

    items_and_values=[]

    with open(file,"r") as file:
        file_reader=csv.DictReader(file,delimiter=";")
        for row in file_reader:
            items_and_values.append([row["Item"],row["Value"]])


    value_for_single_item=[]

    for i in items_and_values:

        if item == i[0]:

            value_for_single_item.append(i[1])


    value_for_single_item.sort()

    return(value_for_single_item[0])


items=items_array(file)

for i in items:
    lv=find_lowest_value(i,file)
    print(i,lv)

由于实际 .csv 文件中的行大约为 25k,而我使用的方法大约需要 30 分钟。我相信它可以做得更快更智能:)

这是预期的结果:

Item    Value
B   2.6
D   4.2
E   5.6
F   3.2
A   1.2
C   5.2

【问题讨论】:

    标签: python-3.x csv


    【解决方案1】:

    如果您使用 Pandas 在 Dataframe 中导入 csv,则无需读取 25k 文件,只需一次。而且会快很多。

    【讨论】:

      【解决方案2】:
      df=pd.read_csv(file,sep=";")
      
      a=df.groupby("Item")["Value"].min()
      

      几乎可以解决问题。两行代码,用了 2 秒就搞定了。熊猫必须是某种魔法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        • 1970-01-01
        • 1970-01-01
        • 2018-05-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多