我有一个csv文件,其中包含一些内容,如下所示:
name,x,y
N1,30.2356,12.5263
N2,30.2452,12.5300
...然后继续。
这是我尝试过的方法,我从.csv中调用了它们,并分别添加到了不同的列表中。
import csv
nn = []
xkoor = []
ykoor = []
coord = []
with open('C:/Users/Mert/Desktop/py/transformation/1.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
nn.append(row[0].split(','))
xkoor.append(row[1].split(','))
ykoor.append(row[2].split(','))
j = 1
for i in range(len(xkoor)):
for j in range(len(ykoor)):
我正在尝试列出以下内容:
coord = [30.2356,12.5263],[30.2452,12.5300],....
,我不知道该怎么做。有什么想法吗?
答案 0 :(得分:2)
默认情况下,csv阅读器应以逗号分隔行:
import csv
with open('somefile.csv') as fh:
reader = csv.reader(fh)
for row in reader:
print(row)
# outputs
['name', 'x', 'y']
['N1', '30.2356', '12.5263']
['N2', '30.2452', '12.5300 ']
考虑到这一点,如果您只是想遍历坐标,则可以使用解包来获取x
和y
,然后通过添加元组来构建列表:
import csv
coords = []
with open('somefile.csv') as fh:
reader = csv.reader(fh)
next(reader) # skips the headers
for row in reader:
name, x, y = row
coords.append((float(x), float(y)))
# then you can iterate over that list like so
for x, y in coords:
# do something
坐标将如下所示:
[(30.2356, 12.5263), (30.2452, 12.53)]
答案 1 :(得分:1)
由于csv.reader
已经为您做到了,因此您不应该用逗号来分隔字符串。只需遍历csv.reader
生成器并根据需要解压缩列即可:
reader = csv.reader(f)
next(reader)
coord = [[float(x), float(y)] for _, x, y in reader]
答案 2 :(得分:0)
似乎您使事情过于复杂了。
如果您要做的只是创建一个仅包含X和Y值的坐标数组,这就是您要实现的方式:
Vector<String> siteIdVector = new Vector<>(siteIdSet);
String first = siteIdVector.firstElement();
String last = siteIdVector.lastElement();
您需要做的就是在每行的基础上提取一个子集,并将其附加到您的coord数组中。无需每次都调用行拆分,也不必为轴创建单独的数组。
K.I.S.S!
(此外,请提个建议-避免您的问题出现PII。无需使用整个Windows文件路径,只需指出它是CSV文件即可。我不需要知道您的名字即可回答问题! )
答案 3 :(得分:0)
为什么不熊猫?!
并且更易于使用
import pandas as pd
df = pd.read_csv('1.csv', header=0)
[[r.x, r.y] for _, r in df.iterrows()]
结果:
[[30.2356, 12.5263], [30.2452, 12.53]]
答案 4 :(得分:0)
我会这样处理:
import csv
# coordinates as strings
with open('some.csv', 'r') as f:
cord = [a for _, *a in csv.reader(f)]
# coordinates as floats
with open('some.csv', 'r') as f:
cord = [[float(x), float(y)] for _, x, y in csv.reader(f)]
[print(xy) for xy in cord]
答案 5 :(得分:0)
如果您喜欢oneliners:
using System;
using System.Linq;
using System.Reflection;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Foo(1, 2, 3, 4, 5)); //outputs 15
}
public static int Foo(params int[] args)
{
return (int)typeof(Program).GetMethod(nameof(Bar), BindingFlags.Public | BindingFlags.Static).Invoke(null, args.Select(v => (object)v).ToArray());
}
public static int Bar(int a, int b, int c, int d, int e)
{
return a + b + c + d + e;
}
}
这产生
data = """name,x,y
N1,30.2356,12.5263
N2,30.2452,12.5300"""
coords = [[x,y]
for line in data.split("\n")[1:]
for _,x,y in [line.split(",")]]
print(coords)