如何向 Pandas DataFrame 添加一个每行增加一的简单计数器列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30995018/
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
How do you add a simple counter column that increases by one in each row to a Pandas DataFrame?
提问by ssteyer
I have been running into this problem a lot. If you have an existing DataFrame in Pandas, and you want to add a row that is simply an increasing count, ie. 0, 1, 2..., what is the most efficient way to do it?
我经常遇到这个问题。如果您在 Pandas 中有一个现有的 DataFrame,并且您想添加一个只是递增计数的行,即。0, 1, 2 ...,最有效的方法是什么?
Thanks!
谢谢!
Sam
山姆
回答by maxymoo
The easiest way might be
最简单的方法可能是
df = df.reset_index()
This will give you a new index starting at 0.
这将为您提供一个从 0 开始的新索引。
You could also do
你也可以这样做
df['counter'] = range(len(df))
回答by GBGOLC
If you want to set a specific starting point that's not zero based, say 100:
如果您想设置一个不是基于零的特定起点,请说 100:
initial_value = 100
df['Counter'] = range(initial_value, len(df) +initial_value)
For negative numbering just multiply initial value by -1:
对于负数,只需将初始值乘以 -1:
initial_value = 100 * -1
df['Counter'] = range(initial_value, len(df) +initial_value)
I
一世

