Python 用行号填充一个新的 Pandas 列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49574817/
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 19:08:43  来源:igfitidea点击:

Fill a new pandas column with row numbers

pythonpandas

提问by michael0196

I have the following DataFrame datawith random index values:

我有以下data带有随机索引值的DataFrame :

      A   B
100   0   7
203   5   4
5992  0  10
2003  9   8
20   10   5
12    6   2

I would like to add a new column 'C' with row numbers. For example:

我想添加一个带有行号的新列“C”。例如:

      A   B   C
100   0   7   0
203   5   4   1
5992  0  10   2
2003  9   8   3
20   10   5   4
12    6   2   5

Thank you for your help!

感谢您的帮助!

回答by jezrael

Use numpy.arangeby length of DataFrame:

numpy.arange按长度使用DataFrame

df['C'] = np.arange(len(df))
print (df)
       A   B  C
100    0   7  0
203    5   4  1
5992   0  10  2
2003   9   8  3
20    10   5  4
12     6   2  5

回答by YOBEN_S

By using reset_index

通过使用 reset_index

df['C'] = df.reset_index().index
df

       A   B  C
100    0   7  0
203    5   4  1
5992   0  10  2
2003   9   8  3
20    10   5  4
12     6   2  5


To generalise:

概括地说:

df['C'] = df.index if df.index.is_monotonic_increasing else range(len(df))
df

       A   B  C
100    0   7  0
203    5   4  1
5992   0  10  2
2003   9   8  3
20    10   5  4
12     6   2  5

回答by kamran kausar

We can add new column with row numbers as first column as following:

我们可以添加行号作为第一列的新列,如下所示:

import pandas as pd
import numpy as np
df = pd.DataFrame({'B': [1, 2, 3], 'C': [4, 5, 6]})

    B   C
0   1   4
1   2   5
2   3   6

df.insert(loc=0, column='A', value=np.arange(len(df)))
    A   B   C
0   0   1   4
1   1   2   5
2   2   3   6