如何计算 CSV 中的值?

扎眼的阳光 python 293

原文标题How can I perform a calculation for values inside CSV?

我有一个“大”CSV 文件,我想对其中的一个“值”进行计算。

从 csv 中提取:

id,active,source,SourceId,latlngs,type,area,fir,Designator,MultipleCode,Name
142,0,N,4204260,"-17652,-32400;-17656,-32229;-17762,-32230;-17730,-32400;",R,"",SBRJ,,"","Area 1              "
264040,0,N,10083080,"29900,8400;29900,10800;29650,10800;29650,8400;"," ","R  ","Area 2 "

并且文件持续了许多兆字节……

我正在执行以下操作:

import csv

with open('example.csv', mode='r') as csv_file:
    csv_reader = csv.DictReader(csv_file)

    for row in csv_reader:
        print(row["Name"],end=',')
        f= row["latlngs"][0:-1].split(sep=';')
        for a in f:
            b= a.split()[0:]
            print (b)

结果我得到:

Area1 ,['-17652,-32400']
['-17656,-32229']
['-17762,-32230']
['-17730,-32400']
Area 2       ,['-17652,-32400']
['-17656,-32229']
['-17762,-32230']
['-17730,-32400']

现在我在名称旁边有了latlngs,我需要划分列表中的每个值,例如;[-17652,-32400'] / 600拥有-29.42 -54['-17656,-32229'] / 600拥有-29.426 -53.715

这样做是我失败的地方。在我添加的最后一行代码之后,我尝试了很多东西。

for a in f:
    a.split(',')[0:]
    x = a[0:].split(sep=',')
    try:
        y = int(x[0])/600
        z = int(x[1])/600
        print (y,z)
    except ValueError as e:
            print (e)

但是在那里,得到计算的是 CSV 文件中的最后一个latlngs

从输出中提取:

Area 500,['32390,-8980']
['31920,-9230']
['31930,-9290']
['32510,-12220']
['33090,-18000']
['32510,-23780']
['31330,-29680']
['31330,-29700']
['30620,-32380']
['30620,-32380']
['31070,-32730']
['31530,-33060']
['32260,-30310']
['33480,-24220']
['33480,-24210']
['34090,-18090']
['34090,-17900']
['33480,-11780']
['33470,-11740']
['32870,-8720']
['32390,-8980']
53.983333333333334 -14.966666666666667
53.2 -15.383333333333333
53.21666666666667 -15.483333333333333
54.18333333333333 -20.366666666666667
55.15 -30.0
54.18333333333333 -39.63333333333333
52.21666666666667 -49.46666666666667
52.21666666666667 -49.5
51.03333333333333 -53.96666666666667
51.03333333333333 -53.96666666666667
51.78333333333333 -54.55
52.55 -55.1
53.766666666666666 -50.516666666666666
55.8 -40.36666666666667
55.8 -40.35
56.81666666666667 -30.15
56.81666666666667 -29.833333333333332
55.8 -19.633333333333333
55.78333333333333 -19.566666666666666
54.78333333333333 -14.533333333333333
53.983333333333334 -14.966666666666667

我能看到(在我有限的视野中)是我无法理解为什么计算和显示的值是最后一个而不是每一个。

原文链接:https://stackoverflow.com//questions/71909694/how-can-i-perform-a-calculation-for-values-inside-csv

回复

我来回复
  • 9769953的头像
    9769953 评论

    您不能划分列表:划分将在列表上操作,而不是在列表中的单个项目上。对于该功能,您需要使用 NumPy(在这种情况下,您也可以开始使用 Pandas 来处理表格数据)。

    在纯 Python 中,使用 CSV 模块,这样的事情可以工作:

    import csv
    
    with open('example.csv', newline='', encoding='utf-8') as fp:
        reader = csv.DictReader(fp)
        for row in reader:
            print(row['Name'], end=', ')
            coords = row['latlngs'][:-1].split(';')
            for coord in coords:
                print(coord)
                lat, lon = [int(item) for item in coord.split(',')]
                lat /= 600
                lon /= 600
                print(lat, lon)
    

    然后,您需要为每一行存储每个单独的纬度和经度(可能在一个列表中),然后将该纬度和经度列表存储在整个文件的另一个结构中。或者直接将它们写入新文件。

    2年前 0条评论
  • Kris的头像
    Kris 评论

    如果您可以随意使用pandas库,您可以尝试这样的事情。

    from pandas import read_csv, DataFrame
    
    
    def transform(lat_long: str):
        # -17652,-32400;-17656,-32229;-17762,-32230;-17730,-32400;
        raw = [ll.split(",") for ll in lat_long.split(';') if ll]
        new_lat_longs = [(float(lat) / 600, float(long) / 600) for lat, long in raw]
        new_lat_longs = ";".join([f"{lat}, {long}" for lat, long in new_lat_longs])
        return new_lat_longs
    
    
    df: DataFrame = read_csv('sorted.csv', index_col=0, header=0)
    df["new_latlngs"] = df["latlngs"].apply(transform)
    df.to_csv('transformed_new.csv')
    

    这基本上是加载 CSV,将转换函数应用于所有行中的每个 latlng 列,并将值设置为新列。

    新的 CSV 看起来像

    id,active,source,SourceId,latlngs,type,area,fir,Designator,MultipleCode,Name,new_latlngs
    142,0,N,4204260,"-17652,-32400;-17656,-32229;-17762,-32230;-17730,-32400;",R,,SBRJ,,,Area 1              ,"-29.42, -54.0;-29.426666666666666, -53.715;-29.60333333333333, -53.71666666666667;-29.55, -54.0"
    264040,0,N,10083080,"29900,8400;29900,10800;29650,10800;29650,8400;", ,R  ,Area 2 ,,,,"49.833333333333336, 14.0;49.833333333333336, 18.0;49.416666666666664, 18.0;49.416666666666664, 14.0"
    
    2年前 0条评论