如何根据使用python

时间:2019-02-09 20:35:21

标签: python-3.x csv

我有一个包含两列的.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中具有不同的值。我想清除重复项,并将值最低的重复项保存在“值”中。

这就是我尝试过的方法,并且可以运行,但是速度很慢并且资源昂贵。我相信有更好的方法,可以使用熊猫或其他任何图书馆,所以请给我一个建议。

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

2 个答案:

答案 0 :(得分:0)

如果使用Pandas在数据框中导入csv,则不必一次读取25k文件。而且会更快。

答案 1 :(得分:0)

df=pd.read_csv(file,sep=";")

a=df.groupby("Item")["Value"].min()

绝大部分技巧。两行代码,花了2秒钟完成。熊猫一定是某种魔术。