Python 如何使用 Pandas 向新列添加增量数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38862293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:32:37  来源:igfitidea点击:

How to Add Incremental Numbers to a New Column Using Pandas

pythonpandasdataframe

提问by MEhsan

I have this simplified dataframe:

我有这个简化的数据框:

ID   Fruit
F1   Apple
F2   Orange
F3   Banana 

I want to add in the begining of the dataframe a new column df['New_ID']which has the number 880that increments by one in each row.

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

The output should be simply like:

输出应该简单地像:

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

I tried the following:

我尝试了以下方法:

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

Any idea how to solve this?

知道如何解决这个问题吗?

Thanks!

谢谢!

采纳答案by Kartik

Here:

这里:

df = df.reset_index()
df.columns[0] = 'New_ID'
df['New_ID'] = df.index + 880

回答by piRSquared

df.insert(0, 'New_ID', range(880, 880 + len(df)))
df

enter image description here

在此处输入图片说明

回答by naman

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

您也可以简单地将您的 Pandas 列设置为长度与数据框相同的 id 值列表。

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

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

参考文档:https: //pandas.pydata.org/pandas-docs/stable/missing_data.html

回答by Alexander

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

回答by Bahati Felix

import numpy as np

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