如何使用熊猫向新栏添加增量数字

我有一个简化的数据框架:

ID   Fruit
F1   Apple
F2   Orange
F3   Banana

我想在数据帧的开头添加一个新的列 df['New_ID'],其中的数字 880每行增加一个。

输出应该简单如下:

New_ID   ID   Fruit
880      F1   Apple
881      F2   Orange
882      F3   Banana

我尝试了以下方法:

df['New_ID'] = ["880"] # but I want to do this without assigning it the list of numbers literally

知道怎么解决吗?

谢谢!

218223 次浏览

Here:

df = df.reset_index()
df = df.rename(columns={"index":"New_ID"})
df['New_ID'] = df.index + 880
df.insert(0, 'New_ID', range(880, 880 + len(df)))
df

enter image description here

df = df.assign(New_ID=[880 + i for i in xrange(len(df))])[['New_ID'] + df.columns.tolist()]


>>> df
New_ID  ID   Fruit
0     880  F1   Apple
1     881  F2  Orange
2     882  F3  Banana

You can also simply set your pandas column as list of id values with length same as of dataframe.

df['New_ID'] = range(880, 880+len(df))

Reference docs : https://pandas.pydata.org/pandas-docs/stable/missing_data.html

import numpy as np


df['New_ID']=np.arange(880,880+len(df.Fruit))
df=df.reindex(columns=['New_ID','ID','Fruit'])

For a pandas DataFrame whose index starts at 0 and increments by 1 (i.e., the default values) you can just do:

df.insert(0, 'New_ID', df.index + 880)

if you want New_ID to be the first column. Otherwise this if you don't mind it being at the end:

df['New_ID'] = df.index + 880

I used the follow code:

df.insert(0, 'id', range(1, 1 + len(df)))

So my "id" columns is:

1, 2, 3, ...

If you have a long, chained expression, and you want to add a column with incrementing values, but you don't know the length of the dataframe (due to some of the chained expressions being groups or aggregations) you can also accomplish this by using assign() and a lambda

df.assign(New_ID = lambda x: range(880, 880 + len(x))