python pandas 打印日期时间对象的特定位置
我在网上查看了其他解决方案,但它们都不适用于我的数据框。 我想获取特定日期时间对象的确切位置,但此代码会产生此 keyerror KeyError: '2018-1-31'
import pandas as pd
data=pd.DataFrame()
dti = pd.date_range("2018-01-01", periods=10, freq="M")
data['dti']=dti
print((data['dti'].loc['2018-1-31'])) # it should print 0 since this date is in the first row
I have looked at other solutions online but none of them work on my dataframe.
I want to get the exact location of a specific datetime object but this code produces this keyerror KeyError: '2018-1-31'
import pandas as pd
data=pd.DataFrame()
dti = pd.date_range("2018-01-01", periods=10, freq="M")
data['dti']=dti
print((data['dti'].loc['2018-1-31'])) # it should print 0 since this date is in the first row
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
'dti' 不是索引,因此您不能直接使用
loc
。您需要首先生成一个布尔系列:输出:
以获取索引:
'dti' is not the index, so you cannot use
loc
directly. You need to generate a boolean Series first:output:
to get the index:
您可以尝试执行以下操作来获取索引(查看答案):
输出为:
如果您想要该范围的索引,您可以使用
&
作为过滤条件,可能如下所示:输出为:
You could try following to get index (see answer):
Output is:
And if you want indices for the range, you could using
&
for the condition to filter, may be something like below:Output is: