You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将DataFrame索引转为Datetime并获取第二列最大值对应时间及相关问题

Answers to Your Pandas Questions

Hey there! Let's walk through your two questions with clear, actionable steps using your sample data.

1. How to Convert Index to Datetime While Keeping Rest of the DataFrame

Your current code pq = pq.index.to_datetime() only creates a standalone DatetimeIndex object—it doesn’t update your original DataFrame’s index or preserve the other columns. To fix this, you just need to assign the converted DatetimeIndex back to your DataFrame’s index:

import pandas as pd

# Your sample DataFrame
pq = pd.DataFrame([203, 250, 318, 786, 321, 135], columns=['metric'])

# Convert index to DatetimeIndex and update the original DataFrame
pq.index = pd.to_datetime(pq.index, unit='ns')

Why this works:

  • pd.to_datetime(pq.index, unit='ns') converts your integer index (0,1,2...) to a DatetimeIndex using nanoseconds as the unit (which matches the 1970-01-01 timestamp output you saw earlier).
  • Assigning this back to pq.index modifies the original DataFrame’s index while keeping all your existing columns completely intact.

2. Equivalent Method for pd.DataFrame.id... (Finding Max Value's Index)

I’m guessing you’re referring to the method that finds the index corresponding to the maximum value in a column—that’s idxmax()! Since you want the datetime index for the maximum value in the second column, here’s how to do it:

# Get the datetime index where the second column (named 'metric' here) has its maximum value
max_value_datetime = pq['metric'].idxmax()

# If you prefer referencing columns by position instead of name:
max_value_datetime = pq.iloc[:, 1].idxmax()

Example Output:

For your sample data, the maximum value is 786 at index 3, so max_value_datetime will return:
Timestamp('1970-01-01 00:00:00.000000003')


内容的提问来源于stack exchange,提问作者Artur Müller Romanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:01:24