import pandas as pd print(pd.Timedelta('5 days 8 hours 6 minutes 59 seconds'))输出结果:
5 days 08:06:59
unit
参数也可以创建一个 Timedelta 对象。
import pandas as pd print(pd.Timedelta(19,unit='h'))输出结果:
0 days 19:00:00
import pandas as pd print (pd.Timedelta(days=2,hours=6))输出结果:
2 days 06:00:00
pd.to_timedelta()
方法,将具有 timedelta 格式的值 (标量、数组、列表或 Series)转换为 Timedelta 类型。如果输入是 Series,则返回 Series;如果输入是标量,则返回值也为标量,其他情况输出 TimedeltaIndex。示例如下:
import pandas as pd print(pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan'])) print(pd.to_timedelta(np.arange(5), unit='s'))输出结果:
TimedeltaIndex(['1 days 06:05:01.000030', '0 days 00:00:00.000015', NaT],dtype='timedelta64[ns]', freq=None) TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:01', '0 days 00:00:02','0 days 00:00:03', '0 days 00:00:04'],dtype='timedelta64[ns]', freq=None)
datetime64[ns]
类型的时间序列或时间戳做算术运算,其运算结果依然是datetime64[ns]
数据类型。接下来,我们创建一个带有 Timedelta 与 datetime 的 DataFrame 对象,并对其做一些算术运算。
import pandas as pd s = pd.Series(pd.date_range('2020-1-1', periods=5, freq='D')) #推导式用法 td = pd.Series([ pd.Timedelta(days=i) for i in range(5)]) df = pd.DataFrame(dict(A = s, B = td)) print(df)输出结果:
A B 0 2020-01-01 0 days 1 2020-01-02 1 days 2 2020-01-03 2 days 3 2020-01-04 3 days 4 2020-01-05 4 days
import pandas as pd s = pd.Series(pd.date_range('20120-1-1', periods=3, freq='D')) td = pd.Series([ pd.Timedelta(days=i) for i in range(3) ]) df = pd.DataFrame(dict(A = s, B = td)) #加法运算 df['C']=df['A']+df['B'] print(df)输出结果:
A B C 0 2020-01-01 0 days 2020-01-01 1 2020-01-02 1 days 2020-01-03 2 2020-01-03 2 days 2020-01-05
import pandas as pd s = pd.Series(pd.date_range('2012-1-1', periods=3, freq='D')) td = pd.Series([ pd.Timedelta(days=i) for i in range(3) ]) df = pd.DataFrame(dict(A = s, B = td)) df['C']=df['A']+df['B'] df['D']=df['C']-df['B'] print(df)输出结果:
A B C D 0 2019-01-01 0 days 2019-01-01 2019-01-01 1 2019-01-02 1 days 2019-01-03 2019-01-02 2 2019-01-03 2 days 2019-01-05 2019-01-03
本文链接:http://task.lmcjl.com/news/16237.html