我對使用 CSV 完全陌生。我已經逐行看到了答案,但我找不到閱讀的行組。我有一個 csv 檔案,例如包含以下資料格式,其中第一行包含開始、月份和日期。從第二行開始,我只有最后兩列的資料,比如 A 和 B。
starting 6 3
34.75 15
34.75 15.25
32.5 14.2
starting 7 27
12.75 14.75
13 15
starting 7 28
29 33
29 33.25
我想要做的是從每個開始的下方檢索資料,并將它們分別撰寫為 3 個陣列的串列,每個陣列有 2 列。這樣做的目的是能夠獨立地繪制每個起始陣列。
這是我經過多次搜索后設法撰寫的代碼,請幫助糾正我遺漏的地方。
import numpy as np
#input file
f=open('./latlon.dat','r')
lines = f.readlines() # Read file and close
f.close()
i = 0
tr = []
while (i < (len(lines)-1) ):
line = lines[i]
i = i 1
linesplit = line.strip().split('\t')
if linesplit[0] == 'start' :
latlog = int(linesplit[1])
latlogarray = np.genfromtxt(lines[i:(i latlog)])
for k in range (i-1,i latlog):
i = i latlogarray
tr.append(k)
print(tr)
謝謝你的期待。
uj5u.com熱心網友回復:
您可以使用 Python 的 CSV 模塊完成此操作。
讀你的問題,你有一組是由一條線分隔starting。該組的資料在該行之后開始。最后,您需要所有組。
如果這是真的,那么您想逐行閱讀,當您閱讀starting第一列中的一行時,保存最后一組(如果存在)并開始一個新組:
#!/usr/bin/env python3
import csv
import pprint
groups = []
group = None
with open('latlon.dat', newline='') as f:
reader = csv.reader(f, delimiter='\t')
for row in reader:
# Normalize all cells at once
row = [cell.strip() for cell in row]
# Deal with "blank" lines
if len(row) == 0 or len(row) == 1:
continue
# Starting new group...
if row[0] == 'starting':
# Save last group, if it exists
if group:
groups.append(group)
# Reset group
group = []
# Don't do anything else with this row
continue
# A "data row"
group.append([float(row[1]), float(row[2])])
groups.append(group)
pprint.pprint(groups)
當我對你的樣本運行它時,我得到:
[
[[34.75, 15.0], [34.75, 15.25], [32.5, 14.2]],
[[12.75, 14.75], [13.0, 15.0]],
[[29.0, 33.0], [29.0, 33.25]]
]
uj5u.com熱心網友回復:
在這種情況下,使用熊貓可能更容易:
import pandas as pd
df = pd.read_csv('./latlon.dat', sep = ' ') # sep is whatever delimiter you want
df.plot() # will plot the three variables together
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/389387.html
上一篇:為什么np.linalg.solve在嘗試求解16x16方程組時會出現錯誤?
下一篇:如何在numpy中對稱地移動陣列
