python - 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)
我该如何纠正?
解决方案
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
,但它仅在将True
s 值索引与附加索引匹配时才有效new_ser
:
ser.loc[mask_new_ser] = new_ser
但是因为不同的时区,丢失了日期时间并得到了Timestamp
s 对象:
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]
推荐阅读
- reactjs - 我可以在路线中使用两个组件吗?我该如何使用?
- django - Django 更新中间件以替换装饰器
- firebase - 在 Firebase 中选择分析位置
- c# - 使用 .Split 拆分字符串并返回第一个整数值(不使用 LINQ)
- clojure - Clojure - 递归使用地图
- rust - 克隆 HashMap
作为 HashMap - unity3d - Library\ScriptAssemblies\Unity.Mathematics.pdb:复制文件失败 - unity 3d
- routes - Here Maps Navigation & Graphhopper 路由引擎
- c# - 如何从多点触控屏幕确认第二次触控选择?
- laravel - Laravel:获取自定义 PostgreSQL 模式的最后一个 id