【发布时间】:2013-07-07 19:21:31
【问题描述】:
我在 csv 文件中有 5000 行数据,如下所示,我想使用 numpy 数组按最后一列 6(即 A、B)分组,因为之后我将在每个组中绘制数据.
Title
Date, Time, Value1, Value2, Value3, Value4, Value5
,, Unit1, Unit2, Unit3,,
2012-04-02,00:00, 85.5333333333333, 4.87666666666667, 8.96, 323.27,A
2012-04-02,00:30, 196.5, 5.49, 8.42, 323.15,B
2012-04-02,01:00, 68.2, 4.47, 7.83, 325.30,A
2012-04-02,01:30, 320.9, 6.77333333333333, 8.05, 326.63,B
当我使用 np.genfromtxt 加载数据时,我必须指定 dtype=None,否则 A 项将变为 NaN How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?
我正在尝试使用 itertools groupby 根据最后一列返回所有值,此处提到:How do I use Python's itertools.groupby()? 但首先,我需要对 numpy 数组进行排序。
我尝试使用高级索引,通过拼接第六列并对其进行排序 Python (Numpy) array sorting IE。 v[v[:,0].argsort()]
但是,这里有一个链接提到 numpy 会将我的记录视为我的 dtype 的一维数组(设置为 none),我在尝试对此进行排序时遇到了相同的索引错误: Numpy Array Column Slicing Produces IndexError: invalid index Exception
问题:
1) 如何根据第 6 列的字符串值使用 groupby 拆分 numpy 数组,以便分别绘制它们?
2) 能够跳过也很好,这样我就可以跳过第一行(标题)和第三行(单位)并留下第二行(列标题)和数据。任何人都知道如何使用可用选项轻松做到这一点?
这是我目前的脚本:
import numpy as np
from matplotlib import pyplot as plt
from itertools import groupby
import csv
regression_data_dp1 = np.genfromtxt(“file.csv”, delimiter=',', skiprows=3, dtype=None)
sortindex = regression_data_dp1[:,6]
#Error is hit at this step:
# sortindex = regression_data_dp1[:,6]
#IndexError: invalid index
regression_data_dp1_sorted = regression_data_dp1[ regression_data_dp1(:,column_WRF_wind_direction).argsort()]
for key, group in groupby(regression_data_dp1, lambda x: x[0]):
print key
with open(“file_" + key.strip() + ".csv", 'w') as data_file:
wr=csv.writer(data_file, quoting=csv.QUOTE_ALL)
for item in (group):
wr.writerow(item)
【问题讨论】:
-
什么是
Title?标题多于数据字段;数据文件是这样的吗? -
@drewk 标题只是文件的描述,即。 “这是……等的报告”。第二行是标题,有7个标题。下一行是单位。然后数据也有 7 列。
标签: python sorting numpy group-by