【发布时间】:2019-11-15 15:05:26
【问题描述】:
我有一个带有日期索引的 pandas 数据框。我可以在给定的日期范围内更新它的一个列,但如果首先创建一个基于它的新列,它就不起作用:
import pandas as pd
df = pd.read_csv('https://pylie.com/dl/readings/bikes-nyc-pylie.csv', index_col=0)
df.index = pd.to_datetime(df.index)
print(df.tail(5))
df.loc['2016-10-29':]['temperature'] = 20.0
print(df.tail(5))
df['temperature_f'] = df['temperature'].copy()
df.loc['2016-10-29':]['temperature'] = 40.0
print(df.tail(5))
输出:
temperature precipitation brooklyn manhattan williamsburg queensboro
date
2016-10-27 8.6 35.81 651 1558 2137 1902
2016-10-28 7.5 0.00 2021 3872 4271 3202
2016-10-29 10.6 0.00 1639 3160 4027 2920
2016-10-30 19.1 14.22 1702 2971 3531 2547
2016-10-31 9.4 0.00 2648 4876 5440 3720
temperature precipitation brooklyn manhattan williamsburg queensboro
date
2016-10-27 8.6 35.81 651 1558 2137 1902
2016-10-28 7.5 0.00 2021 3872 4271 3202
2016-10-29 20.0 0.00 1639 3160 4027 2920
2016-10-30 20.0 14.22 1702 2971 3531 2547
2016-10-31 20.0 0.00 2648 4876 5440 3720
temperature precipitation brooklyn manhattan williamsburg queensboro temperature_f
date
2016-10-27 8.6 35.81 651 1558 2137 1902 8.6
2016-10-28 7.5 0.00 2021 3872 4271 3202 7.5
2016-10-29 20.0 0.00 1639 3160 4027 2920 20.0
2016-10-30 20.0 14.22 1702 2971 3531 2547 20.0
2016-10-31 20.0 0.00 2648 4876 5440 3720 20.0
pandas 版本是 0.24.1
【问题讨论】:
-
不要链接索引
df.loc['2016-10-29':]['temperature'] = 40.0,而是链接df.loc['2016-10-29':,'temperature'] = 40.0。它应该按预期工作。 -
参见this doc中的为什么使用链式索引时分配失败部分。
-
你的工作和共享的文档也有帮助。谢谢@QuangHoang!
标签: python pandas date dataframe indexing