首页 > 解决方案 > SettingWithCopyWarning:不支持对 datetimelike 对象的方法进行修改并被丢弃

问题描述

我有一个这样的系列。(序列)

0   2019-01-01 09:20:00-04:00
1   2019-01-02 09:20:00-04:00
2   2019-01-03 09:20:00-04:00
3   2019-01-04 09:20:00-04:00
4   2019-01-05 09:20:00-04:00

另一个这样的。(new_ser)

2   2019-01-01 09:55:11-05:00

另一个这样的。(mask_new_ser)

0   False
1   False
2   True
3   False
4   False

我正在尝试制作这样的最终系列:

0   2019-01-01 09:20:00-04:00
1   2019-01-02 09:20:00-04:00
2   2019-01-01 09:55:11-05:00
3   2019-01-04 09:20:00-04:00
4   2019-01-05 09:20:00-04:00

以下行工作正常。

ser[mask_new_ser.index] = new_ser[mask_new_ser.index]

但我收到以下警告:

SettingWithCopyWarning: modifications to a method of a datetimelike object are not supported and are discarded. Change values on the original.
  self._setitem_with_indexer(indexer, value)

我该如何纠正?

标签: pythonpython-3.xpandaswarningsseries

解决方案


npandas 0.25.0 中的解决方案:

Series如果需要通过新附加Series使用的索引将新值设置为现有值:

ser.loc[new_ser.index] = new_ser
print (ser)
0    2019-01-01 09:20:00-04:00
1    2019-01-02 09:20:00-04:00
2    2019-01-01 09:55:11-05:00
3    2019-01-04 09:20:00-04:00
4    2019-01-05 09:20:00-04:00
Name: a, dtype: object

另一个解决方案mask,但它仅在将Trues 值索引与附加索引匹配时才有效new_ser

ser.loc[mask_new_ser] = new_ser

但是因为不同的时区,丢失了日期时间并得到了Timestamps 对象:

print (ser.apply(type))
0    <class 'pandas._libs.tslibs.timestamps.Timesta...
1    <class 'pandas._libs.tslibs.timestamps.Timesta...
2    <class 'pandas._libs.tslibs.timestamps.Timesta...
3    <class 'pandas._libs.tslibs.timestamps.Timesta...
4    <class 'pandas._libs.tslibs.timestamps.Timesta...
Name: a, dtype: object

如果需要日期时间,可以转换为UTC

ser = pd.to_datetime(ser, utc=True)
print (ser)
0   2019-01-01 13:20:00+00:00
1   2019-01-02 13:20:00+00:00
2   2019-01-01 14:55:11+00:00
3   2019-01-04 13:20:00+00:00
4   2019-01-05 13:20:00+00:00
Name: a, dtype: datetime64[ns, UTC]

推荐阅读