我正在尝试在python 3中的csv文件中添加一个新列.csv文件有一个标题行,此时我不需要前两列。其他8列包含多边形的4个坐标。我正在尝试添加一个新列,从csv中的点计算区域。我已经看到几个类似的堆栈溢出问题,并试图在我的代码中使用那里的信息,但此刻,只有csv的最后一行显示,我不认为该区域正确计算。有什么建议? (仅供参考,这是我使用csv的第一个代码。) 这是我的代码:
with open(poly.csv, 'rU')as input:
with open ('polyout.csv', 'w') as output:
writer = csv.writer(output, lineterminator='\n')
reader=csv.reader(input)
coords=[]
row =next(reader)
row =next(reader,None)
coords=row[2:]
prev_de=coords[-2]
prev_dn=coords[-1]
prev_de=float(prev_de)
prev_dn=float(prev_dn)
areasq=float(0)
for de,dn in zip(coords[:-1:2], coords[1::2]):
areasq+= (float(de)*float(prev_dn))-(float(dn)*float(prev_de))
prev_de, prev_dn = de,dn
area =abs(areasq)/2
for row in reader:
row.append(area)
coords.append(row)
writer.writerows(coords)
print(row)
答案 0 :(得分:1)
我建议您使用pandas
。
import pandas as pd
df = pd.read_csv('./poly.csv')
df['area'] = calculate_area(df) # implement calculate_area
df.write_csv('polyout.csv')
你可能最好只使用简单的numpy
,看看这个问题的答案Calculate area of polygon given (x,y) coordinates
答案 1 :(得分:0)
我的数据,顺时针给出第1个四边形,逆时针给出第2个
$ cat a.csv
a,b,x1,y1,x2,y2,x3,y3,x4,y4
a,b,3,3,3,9,4,9,4,3
e,f,0,0,5,0,5,5,0,5
$
导入,我导入stdout
以便能够在屏幕上显示我的
结果
from csv import reader, writer
from sys import stdout
使用csv
类
data = reader(open('a.csv'))
out = writer(stdout)
处理标题(假设一行标题)
headers = next(data)
headers = headers+['A']
out.writerow(headers)
循环数据,处理数据,输出处理数据
for row in data:
# the list comprehension is unpacked in aptly named variables
x1, y1, x2, y2, x3, y3, x4, y4 = [int(v) for v in row[2:]]
# https://en.wikipedia.org/wiki/Shoelace_formula#Examples
a = (x1*y2+x2*y3+x3*y4+x4*y1-y1*x2-y2*x3-y3*x4-y4*x1)/2
row.append(a)
out.writerow(row)
我已将上述内容保存在名为area.py
的文件中,最后我们
$ python3 area.py
a,b,x1,y1,x2,y2,x3,y3,x4,y4,A
a,b,3,3,3,9,4,9,4,3,-6.0
e,f,0,0,5,0,5,5,0,5,25.0
$
要使用鞋带配方 ,请记住点必须顺时针排序,如果您的数据不同,只需写a = -(...