Python Pandas - 從 DateTimeIndex 建立 DataFrame 並覆蓋結果列的名稱


要從 DateTimeIndex 建立 DataFrame,請使用 **datetimeindex.to_frame()**。我們使用 name 引數來覆蓋結果列的 **名稱**。

首先,匯入所需的庫:

import pandas as pd

建立一個週期為 5 且頻率為 S(秒)的 DatetimeIndex:

datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='40S')

顯示 DateTimeIndex:

print("DateTimeIndex...\n", datetimeindex)

使用 'False' 引數,原始索引不會設定在返回的 DataFrame 中。為了覆蓋結果列的名稱,我們使用了 'name' 引數:

print("\nDateTimeIndex to DataFrame...\n",
datetimeindex.to_frame(index=False, name = 'DateTimeData'))

示例

以下是程式碼:

import pandas as pd

# DatetimeIndex with period 5 and frequency as S i.e. seconds
# timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='40S')

# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# display DateTimeIndex frequency
print("\nDateTimeIndex frequency...\n", datetimeindex.freq)

# Create a DataFrame from DateTimeIndex
# The original index isn't set in the returned DataFrame using the 'False' parameter
# To override the name of the resulting column, we have used the 'name' parameter
print("\nDateTimeIndex to DataFrame...\n",
datetimeindex.to_frame(index=False, name = 'DateTimeData'))

輸出

這將生成以下程式碼:

DateTimeIndex...
DatetimeIndex(['2021-10-18 07:20:32.261811624+10:30',
'2021-10-18 07:21:12.261811624+10:30',
'2021-10-18 07:21:52.261811624+10:30',
'2021-10-18 07:22:32.261811624+10:30',
'2021-10-18 07:23:12.261811624+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='40S')

DateTimeIndex frequency...
<40 * Seconds>

DateTimeIndex to DataFrame...
DateTimeData
0 2021-10-18 07:20:32.261811624+10:30
1 2021-10-18 07:21:12.261811624+10:30
2 2021-10-18 07:21:52.261811624+10:30
3 2021-10-18 07:22:32.261811624+10:30
4 2021-10-18 07:23:12.261811624+10:30

更新於:2021年10月19日

738 次瀏覽

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.