Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Numpy set dtype=None,无法拼接列,set dtype=object无法设置dtype.names_Python_Numpy - Fatal编程技术网

Python Numpy set dtype=None,无法拼接列,set dtype=object无法设置dtype.names

Python Numpy set dtype=None,无法拼接列,set dtype=object无法设置dtype.names,python,numpy,Python,Numpy,我正在运行Python 2.6。下面的示例中,我尝试从csv文件连接日期和时间字符串列。基于我设置的数据类型(None vs object),我看到了一些我无法解释的行为差异,请参见本文末尾的问题1和2。返回的异常不太具有描述性,并且当dtype设置为object时,dtype文档没有提到任何预期的特定行为 以下是片段: #! /usr/bin/python import numpy as np # simulate a csv file from StringIO import Strin

我正在运行Python 2.6。下面的示例中,我尝试从csv文件连接日期和时间字符串列。基于我设置的数据类型(None vs object),我看到了一些我无法解释的行为差异,请参见本文末尾的问题1和2。返回的异常不太具有描述性,并且当dtype设置为object时,dtype文档没有提到任何预期的特定行为

以下是片段:

#! /usr/bin/python

import numpy as np

# simulate a csv file
from StringIO import StringIO
data = StringIO("""
Title
Date,Time,Speed
,,(m/s)
2012-04-01,00:10, 85
2012-04-02,00:20, 86
2012-04-03,00:30, 87
""".strip())


# (Fail) case 1: dtype=None splicing a column fails

next(data)                                                      # eat away the title line
header = [item.strip() for item in next(data).split(',')]       # get the headers
arr1 = np.genfromtxt(data, dtype=None, delimiter=',',skiprows=1)# skiprows=1 for the row with units
arr1.dtype.names = header                                       # assign the header to names
                                                                # so we can do y=arr['Speed']
y1 = arr1['Speed']  

# Q1 IndexError: invalid index
#a1 = arr1[:,0] 
#print a1
# EDIT1: 
print "arr1.shape " 
print arr1.shape # (3,)

# Fails as expected TypeError: unsupported operand type(s) for +: 'numpy.ndarray' and 'numpy.ndarray'
# z1 = arr1['Date'] + arr1['Time'] 
# This can be workaround by specifying dtype=object, which leads to case 2

data.seek(0)        # resets

# (Fail) case 2: dtype=object assign header fails
next(data)                                                          # eat away the title line
header = [item.strip() for item in next(data).split(',')]           # get the headers
arr2 = np.genfromtxt(data, dtype=object, delimiter=',',skiprows=1)  # skiprows=1 for the row with units

# Q2 ValueError: there are no fields define
#arr2.dtype.names = header # assign the header to names. so we can use it to do indexing
                         # ie y=arr['Speed']
# y2 = arr['Date'] + arr['Time']    # column headings were assigned previously by arr.dtype.names = header

data.seek(0)        # resets

# (Good) case 3: dtype=object but don't assign headers
next(data)                                                          # eat away the title line
header = [item.strip() for item in next(data).split(',')]           # get the headers
arr3 = np.genfromtxt(data, dtype=object, delimiter=',',skiprows=1)  # skiprows=1 for the row with units
y3 = arr3[:,0] + arr3[:,1]                                          # slice the columns
print y3

# case 4: dtype=None, all data are ints, array dimension 2-D

# simulate a csv file
from StringIO import StringIO
data2 = StringIO("""
Title
Date,Time,Speed
,,(m/s)
45,46,85
12,13,86
50,46,87
""".strip())

next(data2)                                                      # eat away the title line
header = [item.strip() for item in next(data2).split(',')]       # get the headers
arr4 = np.genfromtxt(data2, dtype=None, delimiter=',',skiprows=1)# skiprows=1 for the row with units
#arr4.dtype.names = header # Value error
print "arr4.shape " 
print arr4.shape # (3,3)

data2.seek(0)        # resets
问题1:在评论Q1中,当dtype=None时,为什么我不能对列进行切片? 这可以通过以下方式避免: a) arr1=np genfromtxt。。。使用dtype=对象初始化,如案例3所示, b) arr1.dtype.names=。。。注释掉,以避免案例2中的值错误

问题2:在评论Q2,为什么当dtype=object时我不能设置dtype.names

EDIT1:

添加了一个案例4,该案例显示,如果模拟csv文件中的值都是整数,则阵列的维度何时为二维。可以对列进行切片,但分配dtype.names仍然会失败

将术语“拼接”更新为“切片”。

问题1 这是索引,而不是“拼接”,您不能索引到
数据的列中,原因与我之前在对的回答中向您解释的完全相同。看看
arr1。形状
-它是
(3,)
,也就是说
arr1
是1D,而不是2D。没有可供索引的列

现在看一下
arr2
-您将看到它是
(3,3)
。为什么会这样?如果确实指定了
dtype=desired\u type
np.genfromtxt
将对输入字符串的每个分隔部分进行相同的处理(即与
desired\u type
相同),并将返回一个普通的非结构化numpy数组

我不太确定您想用这一行做什么:

z1 = arr1['Date'] + arr1['Time'] 
您的意思是像这样将日期和时间字符串连接在一起:
'2012-04-01 00:10'
?你可以这样做:

z1 = [d + ' ' + t for d,t in zip(arr1['Date'],arr1['Time'])]
这取决于您想对输出执行什么操作(这将提供一个字符串列表,而不是numpy数组)

我应该指出,从1.7版开始,Numpy就有了。这将允许您做更多有用的事情,如计算时间增量等

dts = np.array(z1,dtype=np.datetime64)
编辑: 如果要打印时间序列数据,可以使用
matplotlib.dates.strpdate2num
将字符串转换为matplotlib datenums,然后使用
plot_date()

你还应该看看大熊猫,它们有一些

问题2
无法设置
arr2
名称
,因为它不是结构化数组(见上文)。

感谢您指出结构化数组的名称分配限制。我注意到了这个限制测试,但从文档中我不清楚,所以我发了这篇文章。1) 我打印了arr1.shape,你提到的是(3,3)而不是(3,)。2) 对于z1=arr1['Date']+arr1['Time'],我希望将列中的字符串连接起来,并返回一个numpy数组列,用于绘制时间序列图。3) 仅供参考-我相信通过阅读ndarray docs.python.org/2/library/functions.html#zip的索引页,他们确实将术语“基本切片”称为我试图做的事情。1)我不这么认为-粘贴到numpy v1.7.1中的确切代码副本给了我
arr1.shape==(3,)
。您确定没有混淆变量名吗?2) 查看我的更新。3) 好的,但这是切片,不是“拼接”。我并不想让人觉得我居高临下,但这确实有助于人们理解你的问题。1)对不起,我将测试用例1改为使用dtype=object,它确实是(3,)。我添加了一个案例4,其中输入数据中的所有字段都是int,dtype=None,数组的维数是(3,3)。但是,分配dtype.names仍然会失败,类似于案例2。我在浏览“非结构化numpy数组”的文档,看看是否属于这种情况,但我在中找不到任何关于该术语的参考。2) 谢谢,我已经查看了绘图(日期3)是的,我应该使用正确的术语,并说切片,更新了操作。谢谢。
from matplotlib import dates
from matplotlib import pyplot as pp

# convert date and time strings to matplotlib datenums
dtconv = dates.strpdate2num('%Y-%m-%d%H:%M')
datenums = [dtconv(d+t) for d,t in zip(arr1['Date'],arr1['Time'])]

# use plot_date to plot timeseries
pp.plot_date(datenums,arr1['Speed'],'-ob')