python - 如何使用 Pandas 获得增加值的平均值?

标签 python python-3.x pandas

我正在尝试计算表中每列增加值的平均值。

我的 table

 A  |  B  |  C
----------------
 0  |  5  |  10
100 |  2  |  20
 50 |  2  |  30
100 |  0  |  40

我正在尝试为我的问题编写函数

def avergeIncreace(data,value):  #not complete but what I have so far
  x = data[value].pct_change().fillna(0).gt(0)
  print( x )  

pct_change() 返回该索引处的数字与其之前行中的数字相比的百分比表。fillna(0) 替换 pct_change() 使用 0 创建的图表位置 0 处的 NaNgt(0) 返回 true 或 false 表,具体取决于该索引处的值是否为大于0

该函数的当前输出

In[1]:avergeIncreace(df,'A')
Out[1]:  0    False
         1    True
         2    False
         3    True
         Name: BAL, dtyle: bool

期望的输出

In[1]:avergeIncreace(df,'A')
Out[1]:75
In[2]:avergeIncreace(df,'B')
Out[2]:0
In[3]:avergeIncreace(df,'C')
Out[3]:10

根据我对 pandas 的有限理解,应该有一种方法可以返回所有正确索引的数组,然后使用 for 循环并遍历原始数据表,但我相信 pandas 应该有办法做到这一点没有 for 循环。

我认为 for 循环方式看起来加上缺少代码,因此返回的索引是正确的而不是每个索引

avergeIncreace(df,'A')
  indexes = data[value].pct_change().fillna(0).gt(0).index.values  #this returns an array containing all of the index (true and false)
  answer = 0
  times = 0
  for x in indexes:
    answer += (data[value][x] - data[value][x-1])
    times += 1
  print( answer/times ) 

如何在函数中不使用 for 循环的情况下实现所需的输出?

最佳答案

您可以使用mask()diff():

df.diff().mask(df.diff()<=0, np.nan).mean().fillna(0)

产量:

A    75.0
B     0.0
C    10.0
dtype: float64

关于python - 如何使用 Pandas 获得增加值的平均值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52009303/

相关文章:

python-3.x - 如何从没有扩展名python的路径中获取特定文件名

python - 为什么这不能用作数组成员测试?

python - 为 df rows 中的每个条目创建单行

excel - 使用 Pandas 将一列值与另一列的所有值进行比较

python - 初始化引用文件的实例属性的正确方法是什么?

Python:为什么函数返回一个字典,其中所有值都通过赋值填充?

python - SQL炼金术 : column name prefixed on the subquery of union_all of 3 tables

Python 转换图像以使用更少的颜色

python - 有没有办法对 Pandas 数据框中的一组重复项进行编号?

python - 使用 *list 传递参数不适用于 execl