简体   繁体   English

如何从用户定义的值开始重置 Pandas dataframe 的索引

[英]How to reset the index of a Pandas dataframe starting from a user-defined value

I want to reset the index of a dataframe from a user-defined value, eg 42.我想从用户定义的值(例如42)重置dataframe 的索引。

Let us consider a simple dataframe:让我们考虑一个简单的 dataframe:

import pandas as pd
df=pd.DataFrame({'a':[1,2,3,4,5]})

This answer simply suggests shifting the dataframe's indices:这个答案只是建议改变数据框的索引:

df.index = df.index + 42

This returns:这将返回:

    a
42  1
43  2
44  3
45  4
46  5

But is it possible to use pandas' reset_index method to do the same?但是是否可以使用 pandas 的reset_index方法来做同样的事情?

The best solution that I found so far is to reset the index first and then shift the indices:到目前为止,我发现的最佳解决方案是先重置索引,然后再移动索引:

def reset_index_from_user_defined_value(df, starting_index = 42):
    df = df.reset_index(drop=True)
    df.index = df.index + starting_index
    return df

Is there a better way to achieve this?有没有更好的方法来实现这一目标?

this is one way to do it这是一种方法

set index using an array that starts with the user-defined start value使用以用户定义的起始值开头的数组设置索引

start=42
df.set_index( np.arange(start, start+len(df)))

    a
42  1
43  2
44  3
45  4
46  5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM