如何重新索引熊猫数据框以将起始索引值重置为零? [重复]
Posted
技术标签:
【中文标题】如何重新索引熊猫数据框以将起始索引值重置为零? [重复]【英文标题】:How can I reindex pandas dataframe to reset the starting index value to zero? [duplicate] 【发布时间】:2016-03-14 05:18:03 【问题描述】:在我的数据框中,某些行中有 NaN 值。我想删除这些行。我用 dataframe.dropna(how='any') 解决它。结果如下:
date time open hign low close volume turnover
2 2015-09-01 931 48.60 48.60 48.00 48.00 449700 21741726
3 2015-09-01 932 47.91 48.33 47.91 48.25 158500 7614508
我想重新索引我的数据框的行,所以我运行:
length = dataframe.dropna(how='any').shape[0]
dataframe1 = dataframe.index(range(length))
但是dataframe1仍然保留旧的索引值,比如:
date time open hign low close volume turnover
0 NaN NaN NaN NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN NaN NaN
2 2015-09-01 931 48.60 48.60 48.00 48.00 449700 21741726
3 2015-09-01 932 47.91 48.33 47.91 48.25 158500 7614508
如何让数字以0开头并删除前两行?
想要的结果:
date time open hign low close volume turnover
0 2015-09-01 931 48.60 48.60 48.00 48.00 449700 21741726
1 2015-09-01 932 47.91 48.33 47.91 48.25 158500 7614508
【问题讨论】:
【参考方案1】:重置索引并指定drop=True
。
df = pd.DataFrame('close': [nan, nan, 48.0, 48.25],
'date': [nan, nan, '2015-09-01', '2015-09-01'],
'hign': [nan, nan, 48.60, 48.33],
'low': [nan, nan, 48.0, 47.91],
'open': [nan, nan, 48.60, 47.91],
'time': [nan, nan, 931.0, 932.0],
'turnover': [nan, nan, 21741726.0, 7614508.0],
'volume': [nan, nan, 449700.0, 158500.0])
>>> df
date time open hign low close volume turnover
0 NaN NaN NaN NaN NaN NaN NaN NaN
1 NaN NaN NaN NaN NaN NaN NaN NaN
2 2015-09-01 931 48.60 48.60 48.00 48.00 449700 21741726
3 2015-09-01 932 47.91 48.33 47.91 48.25 158500 7614508
>>> df.dropna(how='any').reset_index(drop=True)
date time open hign low close volume turnover
0 2015-09-01 931 48.60 48.60 48.00 48.00 449700 21741726
1 2015-09-01 932 47.91 48.33 47.91 48.25 158500 7614508
【讨论】:
谢谢。这对我很有帮助。【参考方案2】:您尝试过reindex 功能吗?
【讨论】:
以上是关于如何重新索引熊猫数据框以将起始索引值重置为零? [重复]的主要内容,如果未能解决你的问题,请参考以下文章