【问题标题】:Function to calculate value from first row in Python Pandas从 Python Pandas 中的第一行计算值的函数
【发布时间】:2016-09-22 02:36:12
【问题描述】:

pandas 中是否有任何函数可以模拟 '=sum($A$1:A10'(for 10th row) 之类的 excel 公式,即公式应该从第一行获取滚动数据。

Pandas 滚动函数需要一个整数值作为窗口参数。

【问题讨论】:

  • 滚动窗口的滚动窗口不是 30 参数,有什么方法可以使其动态(行号)。 rolling(30).apply(func=np.percentile,args=(0.90,))。喜欢 excel $A$1:current 单元格公式吗?
  • 我不确定,但看起来需要循环。

标签: python pandas numpy


【解决方案1】:

pandas 中=SUM($A$1:A1) 的等价物是.expanding().sum()(需要pandas 0.18.0):

ser = pd.Series([1, 2, 3, 4])

ser
Out[3]: 
0    1
1    2
2    3
3    4
dtype: int64

ser.expanding().sum()
Out[4]: 
0     1.0
1     3.0
2     6.0
3    10.0

您还可以通过 apply 应用泛型函数:

ser.expanding().apply(lambda x: np.percentile(x, 90))
Out: 
0    1.0
1    1.9
2    2.8
3    3.7
dtype: float64

或者直接用分位数:

ser.expanding().quantile(0.9)
Out[15]: 
0    1.0
1    1.0
2    2.0
3    3.0
dtype: float64

请注意,第 90 个百分位数等于第 0.9 个分位数。然而,Series.quantile 和 Series.expanding.quantile 返回不同的结果,可能是a bug

np.percentile 返回与 Excel 的 PERCENTILE.INC 相同的结果。对于PERCENTILE.EXC,我之前写过一个小函数here

【讨论】:

  • 谢谢..这看起来正是需要的,但百分位值与 excel 值不匹配(可以看到它们甚至在视觉上也不正确)。 percentile(0.9) 应该是 1 1.93 2.86 3.79
  • @ChandanKumar 对于第 90 个百分位数,您需要将 90 作为参数传递。但是,Series.expanding.quantile 似乎有问题,所以现在使用 numpy 版本可能会更好。
猜你喜欢
  • 2022-12-04
  • 1970-01-01
  • 1970-01-01
  • 2017-12-23
  • 1970-01-01
  • 1970-01-01
  • 2019-07-23
  • 2022-12-07
  • 2014-03-31
相关资源
最近更新 更多