当我使用Series.reset_index()
时,我的变量变成DataFrame
对象。有没有什么方法可以重置系列的索引而不会产生此结果?
上下文是基于概率(蒙特卡罗模拟)的随机选择的模拟,其中从系列中做出的选择被 series.pop(item)
省略。
我需要重置索引,因为我要进行迭代以创建累积频率系列。
最佳答案
您可以在.reset_index
中尝试drop=True
,即series.reset_index(drop=True, inplace=True)
根据document :
drop : boolean, default False
Do not try to insert index into dataframe columns.
示例:
series = pd.Series([1,2,3,4,5,1,1])
print(series)
系列结果:
0 1
1 2
2 3
3 4
4 5
5 1
6 1
dtype: int64
从系列中选择一些值:
filtered = series[series.values==1]
print(filtered)
结果:
0 1
5 1
6 1
dtype: int64
重置索引:
filtered.reset_index(drop=True, inplace=True)
print(filtered)
结果:
0 1
1 1
2 1
dtype: int64
使用type(filtered)
仍然返回Series
。
关于python - 重置Series索引而不转为DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49265762/