【发布时间】:2021-10-30 10:30:06
【问题描述】:
我是 python 新手,正在努力计算。我在 CSV 表中有几千行数据,格式如下:
此数据格式错误,因为我的几个 xmin/ymin 值高于 xmax/ymax 值(示例可以在上面的图片链接中看到)。我需要创建新列并使用numpy 或pandas 对数据进行重新排序,以便它们采用正确的格式,例如使用以下代码:
import numpy as np
xmin_new = np.min(xmin, xmax)
xmax_new = np.max(xmin, xmax)
ymin_new = np.min(ymin, ymax)
ymax_new = np.max(ymin, ymax)
问题是我无法在 CSV 中定义列并遍历行来执行此操作。谁能建议我如何修改这个脚本来完成这个?
import pandas
import numpy as np
import os
import csv
#Set cwd
os.chdir("C:\\Users\\desired_directory")
#Open desired csv file
v = open("train.csv")
r = csv.reader(v)
row0 = r.next()
#print header to look at file
print row0
row0.append('xmin_new')
row0.append('xmax_new')
row0.append('ymin_new')
row0.append('ymax_new')
#Check appends
print row0
xmin_new = np.min(xmin, xmax)
xmax_new = np.max(xmin, xmax)
ymin_new = np.min(ymin, ymax)
ymax_new = np.max(ymin, ymax)
#Errors occur here saying that the "xmin_new" column is undefined.
#Also looking to save the file to the directory, but unsure of how to do this properly.
【问题讨论】: