【发布时间】:2018-08-22 06:36:34
【问题描述】:
当我使用Series.reset_index() 时,我的变量变成了DataFrame 对象。有没有办法在不产生这个结果的情况下重置系列的索引?
上下文是基于概率(蒙特卡罗模拟)的随机选择的模拟,其中从系列中做出的选择用series.pop(item) 省略。
我需要重置索引,因为我通过迭代来创建累积频率序列。
【问题讨论】:
标签: python pandas simulation montecarlo
当我使用Series.reset_index() 时,我的变量变成了DataFrame 对象。有没有办法在不产生这个结果的情况下重置系列的索引?
上下文是基于概率(蒙特卡罗模拟)的随机选择的模拟,其中从系列中做出的选择用series.pop(item) 省略。
我需要重置索引,因为我通过迭代来创建累积频率序列。
【问题讨论】:
标签: python pandas simulation montecarlo
您可以在.reset_index 中尝试drop=True,即series.reset_index(drop=True, inplace=True)
根据document:
drop : 布尔值,默认为 False
不要尝试在数据框列中插入索引。
例子:
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。
【讨论】:
series 重新分配给自身,即f = f.reset_index(drop=True, inplace=True),这似乎会清空系列
inplace之后不需要重新赋值,它不返回任何东西,它已经改变了原来的系列f。如果您确实需要分配给其他内容,请删除inplace=True。