Python 熊猫警告与pd.to_日期时间
使用Python 熊猫警告与pd.to_日期时间,python,pandas,Python,Pandas,使用0.6.2。我想将数据帧更改为datetime类型,这是数据帧 >>> tt.head() 0 2015-02-01 00:46:28 1 2015-02-01 00:59:56 2 2015-02-01 00:16:27 3 2015-02-01 00:33:45 4 2015-02-01 13:48:29 Name: TS, dtype: object 我想把tt中的每个项目都改成datetime类型,然后得到hour。代码是 for i
0.6.2
。我想将数据帧更改为datetime
类型,这是数据帧
>>> tt.head()
0 2015-02-01 00:46:28
1 2015-02-01 00:59:56
2 2015-02-01 00:16:27
3 2015-02-01 00:33:45
4 2015-02-01 13:48:29
Name: TS, dtype: object
我想把tt
中的每个项目都改成datetime
类型,然后得到hour
。代码是
for i in tt.index:
tt[i]=pd.to_datetime(tt[i])
而沃林是
__main__:2: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
为什么会出现警告?我该如何处理
如果我每次更改一项,它就工作了,代码是
>>> tt[1]=pd.to_datetime(tt[1])
>>> tt[1].hour
0
只需在整个
系列
上执行此操作,因为to_datetime
可以在类似args的数组上操作,并直接分配给列:
In [72]:
df['date'] = pd.to_datetime(df['date'])
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 1 columns):
date 5 non-null datetime64[ns]
dtypes: datetime64[ns](1)
memory usage: 80.0 bytes
In [73]:
df
Out[73]:
date
index
0 2015-02-01 00:46:28
1 2015-02-01 00:59:56
2 2015-02-01 00:16:27
3 2015-02-01 00:33:45
4 2015-02-01 13:48:29
代码发出呻吟,因为您操作的可能是df上该行的一个副本,而不是视图,使用新代码可以避免这种歧义
编辑
看起来您使用的是一个古老版本的熊猫,以下应该可以使用:
In [80]:
for i in df.index:
df.loc[i,'date']=pd.to_datetime(df.loc[i, 'date'])
df
Out[80]:
date
index
0 2015-02-01 00:46:28
1 2015-02-01 00:59:56
2 2015-02-01 00:16:27
3 2015-02-01 00:33:45
4 2015-02-01 13:48:29
tt[1].apply(lambda x: x.hour)
@unutbu我认为对于单列它是有效的,但我同意这应该是明确的,我想之前我试过
iloc
,然后改为loc
,将更新我知道df['date']=pd.to_datetime(df['date'])
有效,但我想得到每个项目的hour'。在整个
系列中执行`不能将日期与时间分开,我尝试了时间dt.time,但我无法单独获取时间。你可以执行时间df['date'].dt.hour这是一种矢量化方法代码在[72]:ss=pd.to_-datetime(ts)`In[73]:ss[1]
Out[73]:“2015-02-01 00:59:56”在[74]:ss[1]中。小时
>------------------------------------------------------------------
属性错误回溯(最近一次呼叫最后一次)
在()
->1 ss[1].hour
属性错误:“str”对象没有属性“hour”
你误读了我的评论吗?您还需要在出错的地方发布原始数据和代码,这里的ss
是什么?它是系列
?您需要ss[1].dt.hour