用pd.to_datetime警告熊猫
问题内容:
使用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
type,然后获取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
问题答案:
只需对整个数组进行操作即可,Series
就像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
如果将循环更改为此,那么它将起作用:
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
代码mo吟,因为您可能在df上而不是在视图上对该行的副本进行操作,因此使用新的索引器可以避免这种歧义
编辑
看来您使用的是熊猫的古老版本,以下方法应该可以工作:
tt[1].apply(lambda x: x.hour)