Skip to main content
 首页 » 编程设计

python之重新索引数据框 Pandas

2025年05月04日25EasonJim

我正在尝试拆分数据集以使用 Pandas 进行训练和测试。

data = pd.read_csv("housingdata.csv", header=None) 
train = testing.sample(frac=0.6) 
train.reindex() 
test  = testing.loc[~testing.index.isin(train.index)] 
print train 
print test 

当我打印数据时,我得到了

         0     1     2  3      4 
9  0.17004  12.5  7.87  0  0.524 
1  0.02731   0.0  7.07  0  0.469 
5  0.02985   0.0  2.18  0  0.458 
3  0.03237   0.0  2.18  0  0.458 
7  0.14455  12.5  7.87  0  0.524 
6  0.08829  12.5  7.87  0  0.524 
 
         0     1     2  3      4 
0  0.00632  18.0  2.31  0  0.538 
2  0.02729   0.0  7.07  0  0.469 
4  0.06905   0.0  2.18  0  0.458 
8  0.21124  12.5  7.87  0  0.524 

如前所述,行索引被重新排列。如何重新索引两个数据集中的行?

但这不会更改全局设置。例如,

train.iloc[0,4] 

给出 0.524

请您参考如下方法:

正如@EdChum 的评论所指出的,您并不完全清楚您在寻找什么行为。但是,如果您只想为两个新数据帧提供从 0, 1, 2 ... n 开始的索引,那么您可以使用 reset_index() :

train.reset_index(inplace=True, drop=True) 
test.reset_index(inplace=True, drop=True)