gpt4 book ai didi

python - Numpy set dtype=None,不能拼接列和set dtype=object cannot set dtype.names

转载 作者:行者123 更新时间:2023-11-28 17:46:16 25 4
gpt4 key购买 nike

我正在运行 Python 2.6。我有以下示例,我试图连接 csv 文件中的日期和时间字符串列。根据我设置的 dtype(无与对象),我发现一些我无法解释的行为差异,请参阅帖子末尾的问题 1 和 2。返回的异常描述性不强,并且 dtype 文档没有提及将 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... 像案例 3 一样用 dtype=object 初始化,b) arr1.dtype.names=... 被注释掉以避免案例 2 中的值错误

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

编辑 1:

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

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

最佳答案

问题一

这是索引,而不是“拼接”,你不能索引到 data 的列中,原因与我之前在对 Question 7 here 的回答中向你解释的完全相同。 .查看 arr1.shape - 它是 (3,),即 arr1 是一维的,而不是二维的。没有可供您索引的列。

现在查看 arr2 的形状 - 您会看到它是 (3,3)。为什么是这样?如果您确实指定dtype=desired_typenp.genfromtxt 将把输入字符串的每个分隔部分相同 (即作为 desired_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 有 core array types that support datetime functionality .这将使您能够做更多有用的事情,例如计算时间增量等。

dts = np.array(z1,dtype=np.datetime64)

编辑:如果要绘制时间序列数据,可以使用 matplotlib.dates.strpdate2num 将字符串转换为 matplotlib datenums,然后使用 plot_date():

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')

你还应该看看 Pandas,它有一些 nice tools for visualising timeseries data .

问题2

您不能设置 arr2names 因为它不是结构化数组(见上文)。

关于python - Numpy set dtype=None,不能拼接列和set dtype=object cannot set dtype.names,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17739072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com