Python
 Computer >> コンピューター >  >> プログラミング >> Python

PythonPandas-DateTimeIndexで時刻を深夜に変換します


DateTimeIndexで時刻を深夜に変換するには、 DateTimeIndex.normalize()を使用します パンダで。

まず、必要なライブラリをインポートします-

import pandas as pd

期間7と頻度をHi、つまり時間としてDatetimeIndexを作成します-

datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='10H')

DateTimeIndexを表示-

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

日時の時間コンポーネントは、深夜に変換されます。つまり、00:00:00-

print("\nNormalize (converted the time component to midnight)...\n",
datetimeindex.normalize())

以下はコードです-

import pandas as pd

# DatetimeIndex with period 7 and frequency as H i.e. hours
# The timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-10-30 02:30:50', periods=7, tz='Australia/Adelaide', freq='10H')

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

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

# The time component of the date-time is converted to midnight i.e. 00:00:00
print("\nNormalize (converted the time component to midnight)...\n",
datetimeindex.normalize())

出力

これにより、次のコードが生成されます-

DateTimeIndex...
DatetimeIndex(['2021-10-30 02:30:50+10:30', '2021-10-30 12:30:50+10:30',
'2021-10-30 22:30:50+10:30', '2021-10-31 08:30:50+10:30',
'2021-10-31 18:30:50+10:30', '2021-11-01 04:30:50+10:30',
'2021-11-01 14:30:50+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='10H')
DateTimeIndex frequency...
<10 * Hours>

Normalize (converted the time component to midnight)...
DatetimeIndex(['2021-10-30 00:00:00+10:30', '2021-10-30 00:00:00+10:30',
'2021-10-30 00:00:00+10:30', '2021-10-31 00:00:00+10:30',
'2021-10-31 00:00:00+10:30', '2021-11-01 00:00:00+10:30',
'2021-11-01 00:00:00+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)

  1. PythonPandas-ネストされた辞書をマルチインデックスデータフレームに変換

    まず、ネストされた辞書を作成しましょう- dictNested = {'Cricket': {'Boards': ['BCCI', 'CA', 'ECB'],'Country': ['India', 'Australia', 'England']},'Football': {'Boards': ['TFA', 'TCSA', 'GFA'],'Country'

  2. スプレッドシートをPython辞書に変換する方法は?

    スプレッドシートをPython辞書に変換する最も簡単な方法は、パンダなどの外部ライブラリを使用することです。これは、Excelオブジェクトのto_dictのような非常に便利な機能を提供します。これらは次のように使用できます- 例 from pandas import * xls = ExcelFile('my_file.xls') data = xls.parse(xls.sheet_names[0]) print(data.to_dict()) 出力 これにより、出力が得られます- {'id': 10, 'name': "John&