Python Pandas – 使用 TimeDeltaIndex 创建 Series 并设置所得 Series 的索引
使用 Pandas 中的 to_series() 方法从 TimeDeltaIndex 创建一个 Series。使用 index 参数设置所得 Series 的索引。
首先,导入所需的库如下:
import pandas as pd
创建一个 TimeDeltaIndex 对象。我们使用“data”参数设置了时间差数据,例如:
tdIndex = pd.TimedeltaIndex(data = ['10 day 5h 2 min 3us 10ns', '+22:39:19.999999',
'2 day 4h 03:08:02.000045', '+21:15:45.999999'])
显示 TimedeltaIndex,例如:
print("TimedeltaIndex...\n", tdIndex)
将 TimeDeltaIndex 转换为 Series 并使用“index”参数设置所得 Series 的索引,例如:
print("\nTimeDeltaIndex to series with new index...\n",
tdIndex.to_series(index=['Date1','Date2','Date3','Date4']))
实例
以下是实现代码:
import pandas as pd
# 创建一个 TimeDeltaIndex 对象,我们使用“data”参数设置了时间差数据
tdIndex = pd.TimedeltaIndex(data =['10 day 5h 2 min 3us 10ns', '+22:39:19.999999',
'2 day 4h 03:08:02.000045', '+21:15:45.999999'])
# 显示 TimedeltaIndex
print("TimedeltaIndex...\n", tdIndex)
# 返回 TimeDeltas 组件的 DataFrame
print("\nThe Dataframe of the components of TimeDeltas...\n", tdIndex.components)
# 返回 TimeDeltaIndex 作为对象 ndarray 的 datetime.datetime 对象
print("\nReturn TimeDeltaIndex as object ndarray of datetime.datetime objects...\n",
tdIndex.to_pytimedelta())
# 将 TimeDeltaIndex 转换为 Series 并使用“index”参数设置所得 Series 的索引
print("\nTimeDeltaIndex to series with new index...\n",
tdIndex.to_series(index=['Date1','Date2','Date3','Date4']))
输出
执行代码后将会得到一下结果:
TimedeltaIndex...
TimedeltaIndex(['10 days 05:02:00.000003010',
'0 days 22:39:19.999999',
'2 days 07:08:02.000045',
'0 days 21:15:45.999999'],
dtype='timedelta64[ns]', freq=None)
The Dataframe of the components of TimeDeltas...
days hours minutes seconds milliseconds microseconds nanoseconds
0 10 5 2 0 0 3 10
1 0 22 39 19 999 999 0
2 2 7 8 2 0 45 0
3 0 21 15 45 999 999 0
Return TimeDeltaIndex as object ndarray of datetime.datetime objects...
[datetime.timedelta(days=10, seconds=18120, microseconds=3)
datetime.timedelta(seconds=81559, microseconds=999999)
datetime.timedelta(days=2, seconds=25682, microseconds=45)
datetime.timedelta(seconds=76545, microseconds=999999)]
TimeDeltaIndex to series with new index...
Date1 10 days 05:02:00.000003010
Date2 0 days 22:39:19.999999
Date3 2 days 07:08:02.000045
Date4 0 days 21:15:45.999999
dtype: timedelta64[ns]
注意:本文中的代码仅为示例,实际使用时请根据需求进行修改和灵活运用。