Skip to main content
 首页 » 编程设计

python之带有 pd.to_datetime 的 Pandas 警告

2025年04月02日13pander-it

使用 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类型,并得到小时。代码是

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 可以对类似数组的参数进行操作并直接分配给列:

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 

代码会发出呻吟声,因为您可能正在使用新的 indexers 操作 df 上该行的副本而不是 View 。避免了这种歧义

编辑

看起来您使用的是古老版本的 pandas,以下应该有效:

tt[1].apply(lambda x: x.hour)