📜  Python|熊猫索引.copy()

📅  最后修改于: 2022-05-13 01:55:11.067000             🧑  作者: Mango

Python|熊猫索引.copy()

Python是一种用于进行数据分析的出色语言,主要是因为以数据为中心的Python包的奇妙生态系统。 Pandas就是其中之一,它使导入和分析数据变得更加容易。

Pandas Index.copy()函数复制该对象。该函数还将新对象的名称和 dtype 属性设置为原始对象的名称和 dtype 属性。如果我们希望新对象具有不同的数据类型,那么我们可以通过设置函数的 dtype 属性来实现。

注意:在大多数情况下,使用 deep 应该没有功能差异,但如果传递 deep,它将尝试进行 deepcopy。

示例 #1:使用Index.copy()函数将 Index 值复制到新对象并将新对象的数据类型更改为 'int64'

Python3
# 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


Python3
# Change the data type of newly 
# created object to 'int64'
idx.copy(dtype ='int64')


Python3
# 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


Python3
# to make copy and set data type in the datetime format.
idx_copy = idx.copy(dtype ='datetime64')
  
# Print the newly created object
idx_copy


输出 :

让我们创建一个具有“int64”数据类型的对象的副本。

Python3

# Change the data type of newly 
# created object to 'int64'
idx.copy(dtype ='int64')

输出 :

正如我们在输出中看到的那样,该函数返回了原始索引的副本,其 dtype 为“int64”。示例 #2:使用Index.copy()函数制作原始对象的副本。还要设置新对象的 name 属性并将字符串dtype 转换为 'datetime' 类型。

Python3

# 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

输出 :

让我们复制原始对象。

Python3

# to make copy and set data type in the datetime format.
idx_copy = idx.copy(dtype ='datetime64')
  
# Print the newly created object
idx_copy

输出 :

正如我们在输出中看到的,新对象具有日期时间格式的数据,并且它的名称属性也已设置。