簡體   English   中英

Python Pandas - Index'對象沒有屬性'小時'

[英]Python Pandas - Index' object has no attribute 'hour'

我有一個pandas日期框架,以下代碼可以正常工作

df['hour'] = df.index.hour
df['c'] = df['hour'].apply(circadian)

但我試圖使用以下代碼減少制作'小時'coloumn的需要

df['c'] = df.apply(lambda x: circadian(x.index.hour), axis=1)

但我收到錯誤信息

AttributeError: ("'Index' object has no attribute 'hour'", u'occurred at index 2015-09-25 01:00:00')

有人知道怎么做嗎?

方法1:

DateTimeIndex轉換為Series並使用apply

df['c'] = df.index.to_series().apply(lambda x: circadian(x.hour))

方法2:

使用axis=0 ,它沿行索引計算。

df['c'] = df.apply(lambda x: circadian(x.index.hour), axis=0)


使用datetime訪問器dt

df['c'] = df.index.to_series().dt.hour.apply(circadian)

暫無
暫無

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

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