gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:03:55 27 4
gpt4 key购买 nike

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com