将 pandas DataFrame 的索引增加 1

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

Increase index of pandas DataFrame by one

pythonpandas

提问by Toby

I'd like to have my dataframe start with index 1 instead of 0. But somehow I am not getting it:

我想让我的数据框以索引 1 而不是 0 开头。但不知何故我没有得到它:

In[1]: df = pd.DataFrame([[4,7],[10,11],[7,2]],columns=['one', 'two'])
In[2]: df
Out[2]: 
   one  two
0    4    7
1   10   11
2    7    2
In[3]: df.reindex(range(1,len(df)+1))
Out[3]: 
   one  two
1   10   11
2    7    2
3  NaN  NaN

Where did my first row go? What am I getting wrong about reindex()?

我的第一排去了哪里?我对 reindex() 有什么误解?

回答by EdChum

The reindexing does not reassign the index values and preserve the order for that you can assign directly:

重新索引不会重新分配索引值并保留您可以直接分配的顺序:

In [25]:

df.index = range(1,len(df)+1)
df
Out[25]:
   one  two
1    4    7
2   10   11
3    7    2

The docsshow that you are conforming your data to the new index which will introduce NaNvalues where none existed hence why you lost a row, this is why there is a fillnaparam for reindex.

文件表明你符合你的数据,这将引进新的索引NaN,其中没有因此存在,为什么你失去了一排,这就是为什么有一个值fillnaPARAM的reindex

回答by joctee

To increase your index with 1 you can simply modify the index like this, df.index += 1.

要将索引增加 1,您可以简单地修改索引,df.index += 1.

Full example:

完整示例:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame([[4,7],[10,11],[7,2]],columns=['one', 'two'])

In [3]: df
Out[3]:
   one  two
0    4    7
1   10   11
2    7    2

In [4]: df.index += 1

In [5]: df
Out[5]:
   one  two
1    4    7
2   10   11
3    7    2