2016-09-18 27 views
1

你有一个想法,我怎么能从一个numpy日期时间数组中获得元年的一天? 使用我的代码,我只能接收阵列中一个元素的一年中的哪一天。如何获取数组中每个元素的一年中的哪一天? 这里是我的代码(包括你的代码):如何从一个numpy日期时间数组中获取元年的元日?

#import modules 
import numpy as np 
import pandas as pd 
import datetime 
from datetime import datetime 

#date values in an numpy array as int 
data_int = np.array([[20131001, 20131001, 20131001], 
        [20131002, 20131002, 20131002], 
        [20131002, 20131002, 20131002]]) 
#transform the data_int array in a datetime list 
data_list = [pd.to_datetime(pd.Series(x), format="%Y%m%d") for x in data_int] 
#transform the datetime list back to an datetime array with dtype='datetime64[ns]') 
data = np.asarray(data_list, dtype='datetime64', order=None) 
#convert dtype='datetime64[ns]' into a datetime.date object 
data_date = data.astype('M8[D]').astype('O') 
#get the day of the year from the the data_date array. 
day_of_year = data_date[0,1].timetuple().tm_yday 
#274 

这将是巨大的,如果你或其他人有对我来说是个好主意! 谢谢!

回答

0
import numpy as np 
import pandas as pd 

#date values in an numpy array as int 
data_int = np.array([[20131001, 20131001, 20131001], 
        [20131002, 20131002, 20131002], 
        [20131002, 20131002, 20131002]]) 
#transform the data_int array in a datetime list 
data_list = [pd.to_datetime(pd.Series(x), format="%Y%m%d") for x in data_int] 
doy = pd.DataFrame([x.apply(lambda x: x.timetuple().tm_yday) for x in data_list]).values 
print(doy) 

输出:

[[274 274 274] 
[275 275 275] 
[275 275 275]] 
+0

嗨,Ophir Carmi,thx非常感谢您的帮助。现在计算一年中的一天真的很容易!但我还有一个问题。我需要在10月1日开始计算。因此我修改了一下你的代码,它可以工作。但是有一个缺陷 - 输出数组有不同的形状(取而代之(3,3)形状我得到了(3,1)形状。什么是错误的?它必须与迭代有关...如果你有一个想法来解决这个问题。Greetings, – angi

+0

你可以在Awnser2中找到修改的代码。问候, – angi

0

这里是我修改后的代码,这在 1月开始的一年caluculation的一天。不幸的是,在这段代码中,我得到了错误的numpy数组形状。 而不是形状(3,3)我得到一个形状(3.1)。为什么??? 我很高兴能够解决这个问题。

#import modules 
import pandas as pd 
import numpy as np 

#test numpy array 
data_int = np.array([[0., 20131001., 20131001.], 
        [20131002., 20131002., 20131002.], 
        [20131002., 20131002., 20140930.]]) 
#replace zero values with nan in the data_int numpy array 
data_int[data_int==0]=['nan'] 
#transform the data_int array in a datetime list 
data_list = [pd.to_datetime(pd.Series(x), format="%Y%m%d") for x in data_int] 
#create a datetime start date 
start_date = pd.to_datetime(pd.Series('20131001'), format="%Y%m%d") 
#caluculate the day of year. Unfortunately with this function 
#I got an wrong numpy array shape with (3,1) instead of (3.3). 
doy = pd.DataFrame([x.apply(lambda x: x - start_date) for x in data_list]).values 
#print doy. Thats how my result looks right now. 

#array([[  0 
#0 NaT 
#1 0 days 
#2 0 days], 
#  [  0 
#0 1 days 
#1 1 days 
#2 1 days], 
#  [   0 
#0 1 days 
#1 1 days 
#2 364 days]], dtype=object) 

#and that's how my endresult should look like: 
data_out = np.array([[0, 0, 0], 
        [1, 1, 1], 
        [1, 1, 1]]) 
相关问题