In DataFrame df
, I am having index column as Timestamp
in it some values are in format: %Y-%m-%d %H:%M:%S.%f
and other values in format: %Y-%m-%d %H:%M:%S
due to which I am facing issue in Sorting the index crudeoilm =crudeoilm.sort_index()
as well and Data Fomat it also different.
My Code:
import pandas as pd
# Example DataFrame with mixed datetime formats in the index
data = {
'final_lowerband': [None, None, None, None, 6698.0, 6698.0, 6698.0, 6698.0],
'final_upperband': [None, None, None, None, None, None, None, None],
}
index = [
'2024-07-12 20:38:59.667000',
'2024-07-12 19:38:59.957000',
'2024-07-12 19:36:59.897000',
'2024-07-12 19:13:59.870000',
'2024-07-12 18:15:59',
'2024-07-12 21:35:00',
]
df = pd.DataFrame(data, index=index)
# Convert index to DatetimeIndex
df.index = pd.to_datetime(df.index)
# Convert index to desired format
df.index = df.index.strftime('%Y-%m-%d %H:%M:%S.%f')
# Display the DataFrame with the updated index format
print(df)
ERROR 1:
AttributeError: 'Index' object has no attribute 'strftime'
When Tried Sorting Index , without `strfdatetime getting error.
ERROR 2: TypeError: '<' not supported between instances of 'Timestamp' and 'str'
crudeoilm =crudeoilm.sort_index()
Expected Output:
Timestamp final_lowerband final_upperband
2024-07-12 18:15:59 6698.0 NaN
2024-07-12 19:13:59.870000 6698.0 NaN
2024-07-12 19:36:59.897000 NaN NaN
2024-07-12 19:38:59.957000 NaN NaN
2024-07-12 20:38:59.667000 NaN NaN
2024-07-12 21:35:00 6698.0 NaN