将DataFrame索引转为Datetime并获取第二列最大值对应时间及相关问题
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.indexmodifies 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

