Python是进行数据分析的一种出色语言,主要是因为以数据为中心的python软件包具有奇妙的生态系统。 Pandas是其中的一种,使导入和分析数据更加容易。
Pandas Index.copy()函数复制此对象。该函数还将新对象的名称和dtype属性设置为原始对象的名称和dtype属性。如果我们希望新对象具有不同的数据类型,则可以通过设置函数的dtype属性来实现。
用法: Index.copy(name=None, deep=False, dtype=None, **kwargs)
参数:
name:字符串,可选
deep:布尔值,默认为False
dtype:numpy dtype或pandas类型
返回:复制:索引
注意:在大多数情况下,使用Deep应该没有功能上的区别,但是如果通过deep,它将尝试进行深度复制。
范例1:采用Index.copy()复制索引值到新对象并将新对象的数据类型更改为“ int64”的函数
# importing pandas as pd
import pandas as pd
# Creating the Index
idx = pd.Index([17.3, 69.221, 33.1, 15.5, 19.3, 74.8, 10, 5.5])
# Print the Index
idx
输出:
让我们创建一个数据类型为“ int64”的对象的副本。
# Change the data type of newly
# created object to 'int64'
idx.copy(dtype ='int64')
输出:
正如我们在输出中看到的那样,该函数返回了带有'int64'dtype的原始索引的副本。
范例2:采用Index.copy()函数复制原始对象。还要设置新对象的名称属性,并将字符串dtype转换为“ datetime”类型。
# importing pandas as pd
import pandas as pd
# Creating the Index
idx = pd.Index(['2015-10-31', '2015-12-02', '2016-01-03',
'2016-02-08', '2017-05-05'])
# Print the Index
idx
输出:
让我们复制原始对象。
# to make copy and set data type in the datetime format.
idx_copy = idx.copy(dtype ='datetime64')
# Print the newly created object
idx_copy
输出:
从输出中可以看到,新对象具有datatime格式的数据,并且其name属性也已设置。