KranKran
KranKran

Reputation: 21

Use of copy in reindex and saving the newly indexed data

I have the following code:

dat = pd.DataFrame(np.arange(16).reshape(4,4), index = ['a', 'b', 'c', 'd'], columns = ['A', 'B', 'C', 'D'])
dat.reindex(['b', 'c', 'a', 'd'])
dat

However, when I view dat, it still has the index as ['a', 'b', 'c', 'd']. To save dat with the new index, do I have only

dat = dat.reindex(['b', 'c', 'a', 'd'])

as the option? Or is there another way?

Also, when I run the following:

dat.reindex(['b', 'c', 'a', 'd'], copy = False)

it still shows the same index ['a', 'b', 'c', 'd']. I don't understand the use of the copy parameter?

Upvotes: 1

Views: 525

Answers (2)

Scott Boston
Scott Boston

Reputation: 153460

You can use .loc like this instead of reindex (see comments below, best to use reindex):

dat.loc[['b','c','a','d'],:]

Output:

    A   B   C   D
b   4   5   6   7
c   8   9  10  11
a   0   1   2   3
d  12  13  14  15

Upvotes: 0

Roelant
Roelant

Reputation: 5119

You have to save the result to access it. Some functions in pandas take an inplace=True parameter but reindex does not.

dat = dat.reindex(['b', 'c', 'a', 'd'])

To understand the use of the copy parameter, compare:

dat = pd.DataFrame(np.arange(16).reshape(4,4), index = ['a', 'b', 'c', 'd'], columns = ['A', 'B', 'C', 'D'])
x = dat.reindex(['a', 'b', 'c', 'd'], copy=True)
x.iloc[0,0] += 1

with

dat = pd.DataFrame(np.arange(16).reshape(4,4), index = ['a', 'b', 'c', 'd'], columns = ['A', 'B', 'C', 'D'])
x = dat.reindex(['a', 'b', 'c', 'd'], copy=False)
x.iloc[0,0] += 1

Upvotes: 1

Related Questions