【发布时间】: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