PythonPandas-MultiIndexから各レベルの長さのタプルを取得します
MultiIndexから各レベルの長さのタプルを取得するには、 MultiIndex.levshapeを使用します パンダのプロパティ。
まず、必要なライブラリをインポートします-
import pandas as pd
MultiIndexは、パンダオブジェクトのマルチレベルまたは階層的なインデックスオブジェクトです。配列を作成する-
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
「names」パラメーターは、各インデックスレベルの名前を設定します。マルチインデックスの作成に使用されるfrom_arrays()uis-
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student')) 各レベルの長さのタプルを取得します-
print("\nThe tuple with the length of each level in a Multi-index...\n",multiIndex.levshape) 例
以下はコードです-
import pandas as pd
# MultiIndex is a multi-level, or hierarchical, index object for pandas objects
# Create arrays
arrays = [[1, 2, 3, 4, 5], ['John', 'Tim', 'Jacob', 'Chris', 'Keiron']]
# The "names" parameter sets the names for each of the index levels
# The from_arrays() uis used to create a Multiindex
multiIndex = pd.MultiIndex.from_arrays(arrays, names=('ranks', 'student'))
# display the Multiindex
print("The Multi-index...\n",multiIndex)
# get the integer number of levels in Multiindex
print("\nThe number of levels in Multi-index...\n",multiIndex.nlevels)
# get the levels in Multiindex
print("\nThe levels in Multi-index...\n",multiIndex.levels)
# get a tuple with the length of each level
print("\nThe tuple with the length of each level in a Multi-index...\n",multiIndex.levshape) 出力
これにより、次の出力が生成されます-
The Multi-index...
MultiIndex([(1, 'John'),
(2, 'Tim'),
(3, 'Jacob'),
(4, 'Chris'),
(5, 'Keiron')],
names=['ranks', 'student'])
The number of levels in Multi-index...
2
The levels in Multi-index...
[[1, 2, 3, 4, 5], ['Chris', 'Jacob', 'John', 'Keiron', 'Tim']]
The tuple with the length of each level in a Multi-index...
(5, 5) -
PythonPandas-TimeDeltaから日数を取得します
TimeDeltaから日数を取得するには、 timedelta.daysを使用します パンダのプロパティ。まず、必要なライブラリをインポートします- import pandas as pd TimeDeltasは、Pythonの標準の日時ライブラリであり、異なる表現のtimedeltaを使用します。 Timedeltaオブジェクトを作成する timedelta = pd.Timedelta('5 days 1 min 45 s') 日数を返す timedelta.days 例 以下はコードです import pandas as pd # TimeDeltas is
-
Python-PandasのTimestampオブジェクトから平日を取得します
Timestampオブジェクトから平日を取得するには、 timestamp.weekday()を使用します 方法。まず、必要なライブラリをインポートします- import pandas as pd import datetime パンダでタイムスタンプを設定します。タイムスタンプオブジェクトを作成する timestamp = pd.Timestamp(datetime.datetime(2021, 5, 12)) その年の平日を取得します。平日は、月曜日==0、火曜日==1…日曜日==6の数字で表されます。 timestamp.weekday() 例 以下はコードです import