0

How to create a column and reindex in pandas?

I'm a new pandas learner. I have 5 rows dataframe as follow:

   A     B     C     D
0  2.34  3.16  99.0  3.2
1  2.1   55.5  77.5  1
2  22.1  54    89    33
3  23    1.24  4.7   5
4  45    2.5   8.7   99

I want to replace index column 0,1...4 with new index 1 to 5. My expected output is:

   A     B     C     D
1  2.34  3.16  99.0  3.2
2  2.1   55.5  77.5  1
3  22.1  54    89    33
4  23    1.24  4.7   5
5  45    2.5   8.7   99

What I did is I create a new column:

new_index = pd.DataFrame({'#': range(1, 5 + 1 ,1)})

Then I tried to reindex:

df.reindex(new_index)

But I got error: ValueError: Buffer has wrong number of dimensions (expected 1, got 2)

What should I do to reindex the former index? Thanks.

Haven Shi
  • 457
  • 5
  • 14
  • 19

2 Answers2

4

Use set_index

In [5081]: df.set_index([range(1, 6)])
Out[5081]:
       A      B     C     D
1   2.34   3.16  99.0   3.2
2   2.10  55.50  77.5   1.0
3  22.10  54.00  89.0  33.0
4  23.00   1.24   4.7   5.0
5  45.00   2.50   8.7  99.0

Or set values of df.index

In [5082]: df.index = range(1, 6)

In [5083]: df
Out[5083]:
       A      B     C     D
1   2.34   3.16  99.0   3.2
2   2.10  55.50  77.5   1.0
3  22.10  54.00  89.0  33.0
4  23.00   1.24   4.7   5.0
5  45.00   2.50   8.7  99.0

Details

Original df

In [5085]: df
Out[5085]:
       A      B     C     D
0   2.34   3.16  99.0   3.2
1   2.10  55.50  77.5   1.0
2  22.10  54.00  89.0  33.0
3  23.00   1.24   4.7   5.0
4  45.00   2.50   8.7  99.0
Zero
  • 74,117
  • 18
  • 147
  • 154
  • Thanks Zero! But what if my dataframe is very big, say 800 items and probably not an array of incremental integer like ['Alice', 'bob', 'Jeff'.....'Tom']? Because it's complex, I have to use method pd.DataFrame to create a new column called new_index, is there any good way to replace the former index with this new column? – Haven Shi Sep 29 '17 at 18:44
  • Yes, `df.set_index([newlist])` – Zero Sep 29 '17 at 18:45
3

You need .values

df.index=df.index.values+1
df
Out[141]: 
       A      B     C     D
1   2.34   3.16  99.0   3.2
2   2.10  55.50  77.5   1.0
3  22.10  54.00  89.0  33.0
4  23.00   1.24   4.7   5.0
5  45.00   2.50   8.7  99.0

As Per Zero :

df.index += 1
BENY
  • 317,841
  • 20
  • 164
  • 234