我在尝试操作 CSV 文件并将结果附加到新列时遇到了一些问题。
基本上,我有一个 csv 文件(带分隔符的 ;),目前有 5 列(笛卡尔坐标 [X, Y] 和分量 [dX, dY],以及幅度/长度)。我希望将一些方程的结果添加到此 csv 文件的第 6 列(角度)中,这些方程的结果取决于我的笛卡尔分量的值。
到目前为止,我的代码是这样的(数学是正确的[希望如此],只是我遇到问题的附加):
import csv, math
with open("mydata.csv", "rb") as f:
vectors = csv.reader(f, delimiter=";")
for col in vectors:
x = float(col[0])
y = float(col[1])
dX = float(col[2])
dY = float(col[3])
magnitude = float(col[4])
if dX > 0 and dY > 0:
comp = dY/dX
theta = math.degrees(math.atan(comp))
angle = 90 - theta
elif dX > 0 and dY < 0:
comp = dY/dX
theta = math.degrees(math.atan(comp))
angle = 90 + theta
elif dX < 0 and dY > 0:
comp = dX/dY
theta = math.degrees(math.atan(comp))
angle = 360 - theta
elif dX < 0 and dY < 0:
comp = dY/dX
theta = math.degrees(math.atan(comp))
angle = 270 - theta
基本上,我想将 angle 变量添加到第 6 列,用于我的 csv 文件的正确行。
我尝试创建一个新列表并附加(例如):
angles = []
...
angles.append(col)
angles.append(angle)
但是,正如您可能已经猜到的那样,我最终得到了这样一行:
[[x, y, dX, dY, magnitude], angle]
提前感谢您的帮助。
请您参考如下方法:
这个答案为时已晚,因为解决方案已经被接受,但解决问题的最简单方法是将新构建的行直接写入输出 csv 文件,而不创建中间列表。
你可以这样写:
import csv, math
with open("mydata.csv", "rb") as f,\
open("newdata.csv", "wb") as g:
vectors = csv.reader(f, delimiter=";")
writer = csv.writer(g, delimiter=";")
for row in vectors:
# use destructuring
x, y, dX, dY, magnitude = map(float, row)
if dX > 0 and dY > 0:
#<snip>
# at this stage you can write directly to the output
# file.
writer.writerow([x, y, dX, dY, magnitude, angle])
