如何解决如何返回在函数中标识的结果计数? 真假
我有一个函数根据以下函数中定义的条件返回False
和True
:
def find_trend(data,period:int):
'''
Inputs:
takes in a dataframe and an interger
Outputs:
returns True if the trend of the simple moving average over given period is positive,else returns False
'''
data['SMA'] = data['close'].rolling(period).mean()
return (data['SMA']-data['SMA'].shift(1)) > 0
我希望看到返回True
和False
的值的确切数量。
是否可以通过print()
输出此内容?
aapl['trend'] = find_trend(aapl,4)
aapl.trend.head()
0 False
1 False
2 False
3 False
4 False
5 False
6 False
7 True
8 True
9 True
10 False
11 False
12 False
13 False
14 True
15 True
16 True
17 True
18 False
19 False
20 False
21 True
22 False
23 False
24 False
25 True
26 False
27 False
28 False
29 True
解决方法
-
(data['SMA']-data['SMA'].shift(1)) > 0
仅创建一个布尔值。 - 为值和bool创建一个变量,并同时返回两者。
-
data['SMA'] = data['close'].rolling(period).mean()
将就地更新数据框,这意味着SMA
列将被添加到aapl
。
def find_trend(data,period: int):
'''
Inputs:
takes in a dataframe and an interger
Outputs:
returns True if the trend of the simple moving average over given period is positive,else returns False
'''
sma = data['Close'].rolling(period).mean() # creates a series with the rolling mean
diff = sma - sma.shift(1) # calculates a series of values
greater_than_0 = diff > 0 # creates a series of bools
return diff,greater_than_0
aapl['value'],aapl['trend'] = find_trend(aapl,4)
# display(aapl)
Date High Low Open Close Volume Adj Close ticker value trend
0 2019-01-31 169.000000 164.559998 166.110001 166.440002 40739600.0 162.852737 aapl NaN False
1 2019-02-01 168.979996 165.929993 166.960007 166.520004 32668100.0 162.931030 aapl NaN False
2 2019-02-04 171.660004 167.279999 167.410004 171.250000 31495500.0 167.559082 aapl NaN False
3 2019-02-05 175.080002 172.350006 172.860001 174.179993 36101600.0 170.425934 aapl NaN False
4 2019-02-06 175.570007 172.850006 174.649994 174.240005 28239600.0 170.484650 aapl 1.950001 True
5 2019-02-07 173.940002 170.339996 172.399994 170.940002 31741700.0 167.255768 aapl 1.105000 True
6 2019-02-08 170.660004 168.419998 168.990005 170.410004 23820000.0 167.452316 aapl -0.209999 False
7 2019-02-11 171.210007 169.250000 171.050003 169.429993 20993400.0 166.489288 aapl -1.187500 False
8 2019-02-12 171.000000 169.699997 170.100006 170.889999 22283500.0 167.923965 aapl -0.837502 False
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。