Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.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
Arrays 在Python中添加数据_Arrays_Python 2.7_Numpy - Fatal编程技术网

Arrays 在Python中添加数据

Arrays 在Python中添加数据,arrays,python-2.7,numpy,Arrays,Python 2.7,Numpy,我有一个维度为(95,)的时间数据。我编写了以下代码来提取年、月和日,以创建一个维度数组(95,3)。但是,下面的代码能够创建维度数组(285,)。如何创建维度为(95,3)的新时间数组,其中第一列表示年,第二列表示月,最后一列表示日 newtime = np.array([]) for i in range(len(time)): a = seconds_since_jan_1_1993_to_datetime(time[i]) time_year = float(a.strf

我有一个维度为(95,)的时间数据。我编写了以下代码来提取年、月和日,以创建一个维度数组(95,3)。但是,下面的代码能够创建维度数组(285,)。如何创建维度为(95,3)的新时间数组,其中第一列表示年,第二列表示月,最后一列表示日

newtime = np.array([])
for i in range(len(time)):
    a = seconds_since_jan_1_1993_to_datetime(time[i])
    time_year = float(a.strftime("%Y"))
    time_mon = float(a.strftime("%m"))
    time_day = float(a.strftime("%d"))
    newtime = np.append(newtime, np.array([time_year, time_mon, time_day]))
例如,我有一个带有元素数组的输入数组([725696054.99044609,725696056.99082708,725696058.99119401,…])

我想要以下形式的输出:

Col1 Col2 Col3
2015.0 12.0 31.0
2015.0 12.0 31.0
2015.0 12.0 31.0

期待您的建议或帮助。

我的建议是使用数据帧格式

对代码的简单修复方法是:

newtime = pd.DataFrame([], columns=['year','month','day'])

for i in range(len(time)):
    a = seconds_since_jan_1_1993_to_datetime(time[i])
    time_year = float(a.strftime("%Y"))
    time_mon = float(a.strftime("%m"))
    time_day = float(a.strftime("%d"))
    newtime.loc[len(newtime)] = [time_year, time_mon, time_day]

希望有帮助

数据帧是一个很好的选择。但是,如果要保留数组,可以简单地使用numpy的整形()函数。下面是一个示例代码:

import numpy as np

newtime = np.array([])

for i in range(12):
    # Dummy data generated here, using floats like in the original post
    time_year = float(2015.0)
    time_mon = float(1.0*i)
    time_day = float(31.0)
    newtime = np.append(newtime,np.array([time_year, time_mon, time_day]))

newtime = newtime.reshape((-1,3))
注意整形函数中的参数:(-1,3)将告诉numpy使第二个维度为3,自动计算第一个维度。现在,如果打印newtime,您将看到:

[[  2.01500000e+03   0.00000000e+00   3.10000000e+01]
 [  2.01500000e+03   1.00000000e+00   3.10000000e+01]
 [  2.01500000e+03   2.00000000e+00   3.10000000e+01]
 [  2.01500000e+03   3.00000000e+00   3.10000000e+01]
 [  2.01500000e+03   4.00000000e+00   3.10000000e+01]
 [  2.01500000e+03   5.00000000e+00   3.10000000e+01]
 [  2.01500000e+03   6.00000000e+00   3.10000000e+01]
 [  2.01500000e+03   7.00000000e+00   3.10000000e+01]
 [  2.01500000e+03   8.00000000e+00   3.10000000e+01]
 [  2.01500000e+03   9.00000000e+00   3.10000000e+01]
 [  2.01500000e+03   1.00000000e+01   3.10000000e+01]
 [  2.01500000e+03   1.10000000e+01   3.10000000e+01]]

请参见,最好在列表列表中收集值。然后在最后制作一个结构化数组或数据帧。