在python中操作csv文件的行

2024-09-28 21:31:49 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我有一个csv文件,我需要从每一行获取信息,并对其进行操作以产生距离。你知道吗

这是用VBscript编写的代码

' this is just the set up part - don't worry about it
Set thepts = document.componentset("points").OwnedTable
Set theComments = document.ComponentSet("Comments")

' this is all the code you need
for each rec1 in thepts.recordset
 for each rec2 in thepts.recordset
 thedist = ((rec1.Data("X (I)") - rec2.Data("X (I)"))^2 - (rec1.Data("Y     (I)") - rec2.Data("Y (I)"))^2)
 theComments.AddText rec1.Data("OBJECTID")&","&rec2.Data("OBJECTID")&","&thedist &vbcrlf 
 next
 next
 End Sub

抱歉,如果上面的代码看起来不好,我有它保存在记事本,但这里是我目前的python代码看起来像

import csv
import math

f = open('citydata.csv')

csv_f = csv.reader(f)

for row in csv_f:
  for row in csv_f:
    x1 = row[2]
    x2 = row[3]
    x1 = float(x1)
    x2 = float(x2)
    for row in csv_f:
        y1 = row[2]
        y2 = row[3]
        y1 = float(y1)
        y2 = float(y2)
answer = (x1-(math.pow(x2,2)))-(y1-(math.pow(y2,2)))
print(answer)

所以我取(x1-x2^2)-(y1-y2*2)

csv文件的设置如下

第一行=ID IDSP2010 x y long lat ORIG\u FID

然后剩下的行将是信息

唯一重要的信息是x和y下面的数字

因此,我可以考虑如何在c++中使用数组来实现它,但我不能用python来处理它。我以前从未真正使用过python,所以请放轻松,我写了很多文章只是为了确保您理解我所做的一切,如果您感到困惑,请提出任何问题,因为您知道我是


Tags: csv代码infordatamathfloatrow
2条回答

csv_f是一个文件(包装在csv读取器中)。内部循环将读取所有内容。一旦它到达终点,你就不能再阅读了,所以其他的循环就停止了。你知道吗

您需要的是首先将文件中的所有内容复制到内存(data = [x for x in csv_f]),然后应用相同的算法(在data)。你知道吗

同样在python中,缩进也很重要,因此您的公式最后只计算一次。缩进定义for循环或if语句的代码块。从你的VB脚本看来,你希望它计算所有线对。因此,添加制表符/空格以正确对齐它(可能也会打印)。你知道吗

可能还需要删除最外层的循环,因为这将导致程序对文件中的每一行重复所有操作。你知道吗

现在还不太清楚你要干什么,但也许这行得通。您当前正在使用变量名“row”,而且缩进非常奇怪。另外,不应该在循环中包含第一行(标题)。你知道吗

import csv
import math

f = open('citydata.csv')

csv_f = csv.reader(f)
content = [row for row in csv_f]

for row in content[1:]:
    x1 = float(row[2])
    x2 = float(row[3])
    for rowOther in content[1:]:
        y1 = float(rowOther[2])
        y2 = float(rowOther[3])

        answer = (x1-(math.pow(x2,2))) - (y1-(math.pow(y2,2)))

        print(answer)

编辑:

我刚意识到你的x和y在几个地方互换了。请尝试以下操作:

import csv
import math

f = open('citydata.csv')

csv_f = csv.reader(f)
content = [row for row in csv_f]

for row in content[1:]:
    x1 = float(row[2])
    y1 = float(row[3])
    for rowOther in content[1:]:
        x2 = float(rowOther[2])
        y2 = float(rowOther[3])

        answer = (x1-(math.pow(x2,2))) - (y1-(math.pow(y2,2)))

        print(answer)

相关问题 更多 >