Python Pandas TimedeltaIndex.astype()
Python是一种进行数据分析的伟大语言,主要是因为以数据为中心的Python包的奇妙生态系统。Pandas就是这些包中的一个,它使导入和分析数据变得更加容易。
Pandas TimedeltaIndex.astype()函数创建了一个索引,其值被转换成dtypes。新索引的类别由dtype决定。当转换不可能时,会产生一个ValueError异常。
语法: TimedeltaIndex.astype(dtype, copy=True)
参数 :
dtype : numpy dtype 或 pandas type
copy : bool, default True
默认情况下,astype总是返回一个新分配的对象。如果copy被设置为False,并且满足对type的内部要求,原始数据将被用来创建一个新的索引,或者返回原始索引。
返回:索引对象
示例#1:使用TimedeltaIndex.astype()函数将TimedeltaIndex对象的值转换为’str’。
# importing pandas as pd
import pandas as pd
# Create the first TimedeltaIndex object
tidx = pd.TimedeltaIndex(start = '1 days 02:00:12.001124',
periods = 5, freq = 'N', name = 'Koala')
# Print the TimedeltaIndex object
print(tidx)
输出 :
现在我们将使用TimedeltaIndex.astype()函数将该值转换为字符串。
# cast the data values to string format.
tidx.astype('str')
输出 :
正如我们在输出中看到的,TimedeltaIndex.astype()函数已经将tidx对象的值转换为所需格式。
示例#2:使用TimedeltaIndex.astype()函数将TimedeltaIndex对象的值转换为 “bool”。
# importing pandas as pd
import pandas as pd
# Create the TimedeltaIndex object
tidx = pd.TimedeltaIndex(data = ['06:05:01.000030', '+23:59:59.999999',
'22 day 2 min 3us 10ns'])
# Print the TimedeltaIndex object
print(tidx)
输出 :
现在我们将使用TimedeltaIndex.astype()函数将该值转换为bool类型。
# cast the data values to bool type.
tidx.astype('bool')
输出 :
正如我们在输出中看到的,TimedeltaIndex.astype()函数已经将tidx对象的值转换为所需格式。