簡體   English   中英

迭代一個 numpy 數組並調用一個方法

[英]Iterate over a numpy array and call a method

我有個問題。 我想將日期從'2008-09-24''24.09.2008' 我得到的是<function <lambda> at 0x000001CD2B9CE820> 如何遍歷host_since並轉換日期?

host_since = npListings[:,4].astype(np.datetime64) 
# host_since = 
['2008-09-24' '2009-12-02' '2009-11-20' '2010-03-23' '2010-05-13'
 '2010-05-13' '2010-05-25' '2010-07-23' '2009-12-22' '2010-08-08']

get_cubes = lambda x: [datetime.strptime(d, '%y-%m,%d').strftime('%d.%m.%Y') for d in range(host_since.shape[0])]
print(get_cubes)

[OUT]
<function <lambda> at 0x000001CD2B9CE82

我想要的是 get_cubes = ['24.09.2008' ... '08.08.2010'] # 也應該是一個 numpy 數組

正如@Reti43 所提到的,您不妨完全跳過 lambda。

cubes = [datetime.strptime(str(host_since[i]), '%Y-%m-%d').strftime('%d.%m.%Y') 
             for i in range(host_since.shape[0])]
print(cubes)

注意:如果注釋掉的host_since變量中的數據與 numpy 數組中的實際數據相匹配,則您需要將strptime格式更改為%Y-%m-%d

2分:

  • 以您包含的日期為例,在strptime函數中,您的格式錯誤,應該是%Y-%m-%d而不是%y-%m,%d
  • for d in range(host_since.shape[0])迭代整數,對嗎? 那么strptime如何工作的呢?
  • 我們顯然是從所有字符串日期都采用正確的可解析格式的假設開始的 - 請注意,如果不是這種情況,則strptime將拋出ValueError ,因此可能還需要進行一些完整性檢查。

我已將您的代碼改寫如下:

host_since =np.array(\
['2008-09-24', '2009-12-02', '2009-11-20', '2010-03-23', '2010-05-13',
'2010-05-13', '2010-05-25', '2010-07-23', '2009-12-22', '2010-08-08'])

cubes = [datetime.strptime(d, '%Y-%m-%d').strftime('%d.%m.%Y') for d in host_since]

print(cubes)

如果你想使用range ,在我看來你應該寫如下:

cubes = [datetime.strptime(host_since[d], '%Y-%m-%d').strftime('%d.%m.%Y') for d in range(host_since.shape[0])]
print(cubes)

如上所述,在這里使用 lambda 函數是不必要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM