python pandas 打印日期时间对象的特定位置

发布于 2025-01-12 22:58:22 字数 341 浏览 1 评论 0原文

我在网上查看了其他解决方案,但它们都不适用于我的数据框。 我想获取特定日期时间对象的确切位置,但此代码会产生此 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

阿楠 2025-01-19 22:58:22

'dti' 不是索引,因此您不能直接使用 loc。您需要首先生成一个布尔系列:

data.loc[data['dti'].eq('2018-1-31'), 'dti']

输出:

0   2018-01-31
Name: dti, dtype: datetime64[ns]

以获取索引:

data.loc[data['dti'].eq('2018-1-31'), 'dti'].index

'dti' is not the index, so you cannot use loc directly. You need to generate a boolean Series first:

data.loc[data['dti'].eq('2018-1-31'), 'dti']

output:

0   2018-01-31
Name: dti, dtype: datetime64[ns]

to get the index:

data.loc[data['dti'].eq('2018-1-31'), 'dti'].index
假装不在乎 2025-01-19 22:58:22

您可以尝试执行以下操作来获取索引(查看答案):

data[data['dti']=='2018-01-31'].index[0]

输出为:

0

如果您想要该范围的索引,您可以使用 & 作为过滤条件,可能如下所示:

data[(data['dti']>'2018-2-28') & (data['dti']<'2018-6-30')].index.tolist()

输出为:

[2, 3, 4]

You could try following to get index (see answer):

data[data['dti']=='2018-01-31'].index[0]

Output is:

0

And if you want indices for the range, you could using & for the condition to filter, may be something like below:

data[(data['dti']>'2018-2-28') & (data['dti']<'2018-6-30')].index.tolist()

Output is:

[2, 3, 4]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文