我正在尝试计算表中每列增加值的平均值。
我的 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/