Python | Pandas Index.copy ()

Index.copy() Pandas Index.copy() makes a copy of this object. The function also sets the name and dtype of the new object as an attribute of the original object. If we want to have a different data type for the new object, we can do so by setting the dtype attribute of the function.

Syntax: Index.copy (name = None, deep = False, dtype = None, ** kwargs)

Parameters:
name: string, optional
deep : boolean, default False
dtype: numpy dtype or pandas type

Returns: copy: Index

Note: in most cases there should be no functional difference from using deep, but if deep is passed it will try to deep copy.

Example # 1: Use Index.copy () to copy the Index value into a new object and change the data type of the new object to int64.

# import pandas as pd

import pandas as pd

 
# Create index

idx = pd.Index ([ 17.3 , 69.221 , 33.1 , 15.5 , 19.3 , 74.8 , 10 , 5.5 ])

  
# Print index
idx

Output:

Let`s create a copy of an int64 object.

# Change data type again
# created an object in & # 39; int64 & # 39;

idx.copy (dtype = ` int64` )

Output:

As we see in the output, the function returned a copy of the original index with the int64 type.

Example # 2: Use Index.copy () to make a copy of the original object. Also set the name attribute of the new object and convert the string d to datetime.

# import pandas as pd

import pandas as pd

 
# Create index

idx = pd.Index ([ `2015-10-31` , `2015-12-02` , ` 2016-01-03`

`2016-02-08` , `2017-05-05` ])

 
# Print index
idx

Output:

Let`s make a copy of the original object.

# make a copy and set the data type in datetime format

idx_copy = idx.copy (dtype = `datetime64` )

  
# Print the newly created object
idx_copy

Output:
 
As we can see in the output, the new object has data in datatime format, and its name attribute has also been set.