如何将计算应用于文本文件列?

问题描述 投票:1回答:2

我正在尝试将计算应用于我的csv文件中每列的每个值,并用这些新的计算值替换旧值。

#temp_list is a list of lists. Eg. [['1.3','2.2','1.6'],['1.2','4.5','2.3']]
for row in temp_list:
    minimum = min(row) #find minimum value of values in column 2
    y = every value in the 2nd column - minimum

    #for every value in the 2nd column, apply y calculation to it and replace original values with these values
    row[1] = float(row[1])

我明白,如果我这样做的话

row[1] = float(row[1]) * 3

例如,我会将第2列(索引1)中的每个值乘以3.我如何为上面写的y计算做到这一点?

python python-3.x csv
2个回答
0
投票

您可以使用zip转置列表列表,将序列转换为列表,然后使用[1]获取第二行(最初的第二列)中的值,以便您可以使用min函数和float作为关键函数根据浮点值来获取最小值:

min(list(zip(*temp_list))[1], key=float)

这将返回:2.2


0
投票

根据您的评论,我认为这是您想要的。因为你的列表是字符串,所以在Decimalstring之间有一些来回摆动

from decimal import Decimal
temp_list = [['1.3','2.2','1.6'],['1.2','4.5','2.3']]

for x in temp_list:
  x[1] = str(Decimal(x[1]) - min(Decimal(y) for y in x))

print(temp_list)
# [['1.3', '0.9', '1.6'], ['1.2', '3.3', '2.3']]
© www.soinside.com 2019 - 2024. All rights reserved.