如何在 pandas 数据框中插入列名? [英] how to insert column name in pandas dataframe?

查看:84
本文介绍了如何在 pandas 数据框中插入列名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框

             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

我想添加一个从索引1开始的doc-id列,并将列0的值更改为value。
预期输出为

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
        ...

我该怎么做?

推荐答案

使用 插入 ,然后重命名

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

如果需要更改索引,请添加 1 ,然后使用重命名 rename_axis

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

这篇关于如何在 pandas 数据框中插入列名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆