Python 计算列中的正值
我有一个多列数字的表格。我正在尝试获取此表的统计数据,但我一直在尝试计算单个列中行与行之间的正增长量 我所拥有的Python 计算列中的正值,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有一个多列数字的表格。我正在尝试获取此表的统计数据,但我一直在尝试计算单个列中行与行之间的正增长量 我所拥有的 A | B | C -------------- 1 | 5 | 2 5 | 2 | 7 2 | 2 | 10 18 | 0 | 14 我正试图为我的问题编写函数 def countIncreace(data,value): #not complete but what I have so far print( data[value].p
A | B | C
--------------
1 | 5 | 2
5 | 2 | 7
2 | 2 | 10
18 | 0 | 14
我正试图为我的问题编写函数
def countIncreace(data,value): #not complete but what I have so far
print( data[value].pct_change().fillna(0).count( > 0) )
pct\u change()
返回该索引处的数字与前一行数字的百分比表,并且fillna(0)
将pct\u change()
创建的图表位置0处的NaN
替换为0
我的期望输出:
[IN]>countIncreace(df, 'A'):
[OUT]> 2
[IN]>countIncreace(df, 'B'):
[OUT]> 0
[IN]>countIncreace(df, 'C'):
[OUT]> 3
我在函数中遗漏了什么,以使正值的计数非常接近!除了您试图计算大于0的百分比变化数的方式外,所有操作都是正确的。这里有一种方法
def countIncrease(df,column):
print sum(df[column].pct_change().fillna(0) > 0)
你可以用
例如:
df = pd.DataFrame(np.random.randint(-10, 10, (3, 3)), columns=list('ABC'))
print(len(df.loc[df.A > 0]))
或者只是[
]
:
print(len(df[df.A > 0]))
您可以使用
pd.Series
方法gt
(大于)和sum
:
df[column].pct_change().fillna(0).gt(0).sum()
一般来说,这比在Pandas series/NumPy阵列中使用内置函数更好
df[column].pct_change().fillna(0).gt(0).sum()