Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 有没有更简单的方法来更改数据帧的索引值?_Python_Pandas_Dataframe_Reindex - Fatal编程技术网

Python 有没有更简单的方法来更改数据帧的索引值?

Python 有没有更简单的方法来更改数据帧的索引值?,python,pandas,dataframe,reindex,Python,Pandas,Dataframe,Reindex,我获取一个数据帧,将其分为两个数据帧,然后我需要更改索引值,以便没有任何数字大于总行数 代码如下: dataset = pd.read_csv("dataset.csv",usecols['row_id','x','y','time'],index_col=0) splitvalue = math.floor((0.9)*786239) train = dataset[dataset.time < splitvalue] test = dataset[dataset.time >

我获取一个数据帧,将其分为两个数据帧,然后我需要更改索引值,以便没有任何数字大于总行数

代码如下:

dataset =   pd.read_csv("dataset.csv",usecols['row_id','x','y','time'],index_col=0)
splitvalue = math.floor((0.9)*786239)
train = dataset[dataset.time < splitvalue]
test = dataset[dataset.time >= splitvalue]
有更好的方法吗?

试试:

test = test.reset_index(drop=True).rename_axis('row_id')

您应该在切片之前洗牌数据

dataset.reindex(np.random.permutation(dataset.index))

否则,您可能会对测试/列车组产生偏差

您可以直接指定一个新的
索引
对象来覆盖索引:

test.index = pd.Index(np.arange(len(df)), name='row_id')

谢谢你的建议。我没有意识到洗牌可以通过重新编制索引来完成。酷。@LarryFreeman,不要在新数据框上用head检查。。头部在索引上排序,然后显示。。。有一段时间让我发疯。如果我不使用head()检查,还有什么选择?我并不聪明,我只是在Ipython笔记本电脑中使用了上面的命令,看起来排名前五。。。你可以用花哨的索引进行切片,我没有试过。
test.index = pd.Index(np.arange(len(df)), name='row_id')