python - 重置Series索引而不转为DataFrame

标签 python pandas simulation montecarlo

当我使用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/

相关文章:

python混合单双unicode转义序列

python - 按天对数据框进行排序,但不包括年份

python - Pandas 数据框分组

pandas - 使用多个条件从 pandas DataFrame 中删除行

java - 我正在尝试在java中模拟直接映射的缓存。关于使用哪种数据结构来表示缓存有什么想法吗?

python - Alembic:从脚本内的模式比较获取 SQL 输出

python - 如何修复单链表方法追加中的错误

python - 建议为达到最大连接限制而引发的异常类型

c - 分配一个包含 3d 链表的结构体

wpf - 是否曾在 WPF 或 Silverlight 中做过布料模拟?