有一个销售数据框,其索引类型为:日期-时间。
rng = pd.date_range('2015-01-03', periods=500)
df = pd.DataFrame({'historical_sales': np.random.choice([100,200,300],
size=500)}, index=rng)
print (df)
我们还有一个特殊日期列表,some_dates:
some_dates = ['3/15/2017, '6/14/2017'.....]
尝试按某些日期对数据帧进行子集化:
print(df.loc[some_dates])
我收到一个关键错误:“[索引] 中没有任何[[日期]]。 这是因为我正在设置字符串列表而不是日期时间吗?
作为一种解决方法,为了对数据帧进行子集化,这有效:
container = []
for i in some_dates:
container.append(df.loc[i])
dfNew = pd.DataFrame(container)
但我想进一步了解错误的原因以及解决方法是否不是“不良约定”。
最佳答案
我认为需要转换为日期时间,因为按日期时间列表选择:
some_dates = pd.to_datetime(['3/15/2016', '3/14/2016'])
更一般的是 get intersection
datetimeindex
和 some_dates
之间:
some_dates = pd.to_datetime(['3/15/2016', '6/14/2016'])
idx = df.index.intersection(some_dates)
print(df.loc[idx])
<小时/>
But i would like to further understand the reason of the error and if the workaround is not a 'bad convention'.
在我看来,pandas 的主要原因是如果存在另一个通常是矢量化的解决方案,最好避免所有循环。而且循环明显更慢。
您还可以查看this .
关于python - 索引和 for 循环解决方法中没有日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49400488/