1

I have the following dataframe

             0
0     0.164560
1     0.000000
2     0.350000
3     0.700000
    ...
3778  0.350000
3779  0.000000
3780  0.137500
3781  0.253333

I want to add an doc-id column starting with index 1 and change the value of column 0 to value. Expected output is

doc-id       value
    1     0.164560
    2     0.000000
    3     0.350000
    4     0.700000
        ...

How can I do that?

Samuel Mideksa
  • 423
  • 8
  • 19

2 Answers2

2

Use insert and then rename:

df.insert(0, 'doc-id', df.index + 1)
df = df.rename(columns={0:'value'})

print (df)
      doc-id     value
0          1  0.164560
1          2  0.000000
2          3  0.350000
3          4  0.700000
3778    3778  0.350000
3779    3779  0.000000
3780    3780  0.137500
3781    3781  0.253333

If need change index add 1 and then use rename with rename_axis:

df.index +=1
df = df.rename(columns={0:'value'}).rename_axis('doc-id')
print (df)
           value
doc-id          
1       0.164560
2       0.000000
3       0.350000
4       0.700000
3779    0.350000
3780    0.000000
3781    0.137500
3782    0.253333
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
2

If you want to treat this new column as an Index for the dataframe (as opposed to a column of data):

# adjust the index to start at 1 instead of 0
df.reindex(df.index+1, copy=False)
# add the doc_id name
df.index.name = "doc_id"
tegancp
  • 1,204
  • 6
  • 13