【问题标题】:Create array from csv file and data is all in one field从 csv 文件创建数组,数据都在一个字段中
【发布时间】:2017-10-14 05:26:32
【问题描述】:

我的最终目标是将我的 lat long 从已创建的 csv 文件中获取到数组中,然后在 shp 文件中创建多边形。我有 10 条记录可以创建 10 个多边形。我不知道如何解决的问题是 csv 文件的操作。与一个多边形相关的所有经纬度坐标都在一个字段(单元格)中。即:我的列名是“lat_long”,其中只有一个字段中有 15 个以上的数字。每 2 个数字代表多边形的一个点的纬度,如下所示:2089,15663,2103,15664 等。

我的数据现在看起来像这样:

样本 lat_long 检查产品

1 2071、15600、2089、15663、2103、15664 wfc粉碎

2 2071, 15601, 2089, 15663, 2104,15660 qpf 苹果

3 1981、15541、2005、15571、2028、15570 天文番茄

我希望它看起来像这样:

样本经纬度检查产品

1 20.71 -156 wfc 粉碎

1 20.89 -156.66 wfc 暗恋

1 21.03 -156.64 wfc 暗恋

2 20.71 -156.01 qpf 苹果

2 20.89 -156.63 qpf 苹果

2 21.03 -156.64 qpf 苹果

3 19.81 -155.41 天文番茄

3 20.05 -155.71 天文番茄

3 20.28 -155.7 天文番茄

【问题讨论】:

  • 您好,欢迎您。您当前状态的问题非常不清楚,人们很难帮助您。尝试发布所有相关部分 - 您的 csv,以及您的代码与 csv 之间的关系等。发布证明您的问题的 Minimal, Complete, and Verifiable example (MCVE) 将帮助您获得更好的答案。
  • 您可以拆分, 提交的读入,但是查看您拥有的数据如何知道值是负数还是正数? csv 文件是如何创建的?改变它可能更容易/更可靠。
  • 所以2089,15663 变成(20.89, -156.63) 我知道. 来自哪里。但是- 减号?你怎么知道15663 是否定的?

标签: python arrays csv gis


【解决方案1】:
import csv


# Open a new csv to write to
with open("output.csv", "w", newline='') as out_file:
    writer = csv.writer(out_file)

    # Write the header row
    writer.writerow(['Sample', 'lat', 'long', 'check', 'prod'])

    # Open the source .csv file.  You'll need it
    # to be in the same directory as this script.
    with open("data.csv", newline='') as in_file:
        csv_reader = csv.reader(in_file)

        row_num = 0
        for row in csv_reader:
            # Skip the header row of the input data
            if row_num > 0:
                num_columns = len(row)

                sample = int(row[0])
                check = row[num_columns - 2]
                prod = row[num_columns - 1]

                # Loop through the columns by 2 columns at a time
                for col in range(1, num_columns - 2, 2):
                    # Get the raw lat long data
                    raw_lat = row[col]
                    raw_lng = row[col + 1]

                    # Split the lat into components and parse as a float
                    lat = float(raw_lat[0:-2] + '.' + raw_lat[-2:])

                    # Split the long into components and parse as a float
                    lng = float(raw_lng[0:-2] + '.' + raw_lng[-2:])

                    out_row = [sample, lat, lng, check, prod]
                    writer.writerow(out_row)

            row_num += 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多