获取一列中有向量的 csv c(,)

我使用 R 来准备数据,但我发现自己被迫使用 python。csv 文件已存储为 sf 数据框,其中列几何形状存储经度和纬度。在我的文件中,我有以下结构:


a,geometry,b

50,c(-95.11, 10.19),32.24

60,,c(-95.12, 10.27),22.79

70,c(-95.13, 10.28),14.91

80,c(-95.14, 10.33),18.35

90,c(-95.15, 10.5),28.35

99,c(-95.16, 10.7),48.91

这里的目的是在知道 c(-95.11, 10.19) 是 lon 和 lat 2 个值的情况下读取文件,以便它们可以存储在两个不同的列中。然而,将分隔符放在值内(也不是字符串)使得这真的很难做到。


预期输出应该是:


a,long,lat,b

50,-95.11, 10.19,32.24

60,,-95.12, 10.27,22.79

70,-95.13, 10.28,14.91

80,-95.14, 10.33,18.35

90,-95.15, 10.5,28.35

99,-95.16, 10.7,48.91


冉冉说
浏览 61回答 2
2回答

慕后森

这是否有效(输入文件:data.csv;输出文件:data_out.csv):import csvwith open('data.csv', 'r') as fin, open('data_out.csv', 'w') as fout:    reader, writer = csv.reader(fin), csv.writer(fout)    next(reader)    writer.writerow(['a', 'long', 'lat', 'b'])    for row in reader:        row[1] = row[1][2:]        row[2] = row[2][1:-1]        writer.writerow(row)在您的示例输出中,第二列之后是空白:这是有意的吗?,另外,您的示例输入在第一列之后的第二行中有一个双精度?

千万里不及你

如果您正在寻找基于 R 的解决方案,您可以考虑将坐标从{sf}基于几何列提取到常规列中,并相应保存。考虑这个例子,它建立在三个半随机的北卡罗来纳州城市上:library(sf)library(dplyr)cities <- data.frame(name = c("Raleigh", "Greensboro", "Wilmington"),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;x = c(-78.633333, -79.819444, -77.912222),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;y = c(35.766667, 36.08, 34.223333)) %>%&nbsp;&nbsp; st_as_sf(coords = c("x", "y"), crs = 4326)cities # a class sf data.frameSimple feature collection with 3 features and 1 fieldgeometry type:&nbsp; POINTdimension:&nbsp; &nbsp; &nbsp; XYbbox:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;xmin: -79.81944 ymin: 34.22333 xmax: -77.91222 ymax: 36.08geographic CRS: WGS 84&nbsp; &nbsp; &nbsp; &nbsp; name&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;geometry1&nbsp; &nbsp; Raleigh POINT (-78.63333 35.76667)2 Greensboro&nbsp; &nbsp; POINT (-79.81944 36.08)3 Wilmington POINT (-77.91222 34.22333)mod_cit <- cities %>%&nbsp;&nbsp; mutate(long = st_coordinates(.)[,1],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;lat = st_coordinates(.)[,2]) %>%&nbsp;&nbsp; st_drop_geometry()mod_cit # a regular data.frame&nbsp; &nbsp; &nbsp; &nbsp; name&nbsp; &nbsp; &nbsp; long&nbsp; &nbsp; &nbsp; lat1&nbsp; &nbsp; Raleigh -78.63333 35.766672 Greensboro -79.81944 36.080003 Wilmington -77.91222 34.22333
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python