我有一个如下所示的数据框:
Date Last
2016-11-03 101.58
2016-11-04 100.50
2016-11-07 103.55
2016-11-08 104.63
2016-11-09 106.15
2016-11-10 107.65
2016-11-11 106.74
2016-11-14 108.22
2016-11-15 107.92
2016-11-16 106.03
Run Code Online (Sandbox Code Playgroud)
和一个简单的函数:
def new_def(x):
add=70.00
return x[0]+add
Run Code Online (Sandbox Code Playgroud)
我想使用该函数向数据框添加另一列,但我只想将其应用于“2016-11-09”之前的日期。我尝试这样做:
df['New']= df[:'2016-11-09'].apply(new_def, axis=1)
Run Code Online (Sandbox Code Playgroud)
生成的列在“2016-11-09”之前都是正确的,之后为 NaN。关于如何在“2016-11-09”之前返回“x[0] + add”以及之后返回“x[0]”有什么建议吗?
提前致谢
我有一个看起来像这样的DataFrame:
a b
1 0.9 0.796522123
2 0.8 0.701075019
3 0.6 0.777130253
4 0.5 0.209912906
5 0.75 0.920537662
6 1 0.955212665
7 3.5 0.227221963
8 2 0.336632891
9 1.25 0.563511758
10 1 0.832624112
Run Code Online (Sandbox Code Playgroud)
我想创建一个最大周期为3的移动平均线,每次观察都是df['a']*df['b].
如果df['a'].rolling(window=3).sum() <= 3,那么MA将是:
df['MA'] = (df['a']*df['b']).rolling(window=3).mean().
但是,例如,如果df['a'].rolling(window=3).sum() > 3情况如此df[8:10],那么我希望移动平均线为:
((1*0.83)+(1.25*0.832624112)+(0.75*0.336632891))/3.
我一直在玩弄创建一个函数,然后应用它,如:
def MA(a, b, period):
total = 0
sum_a = 0
for i in (b):
if sum_a < period:
sum_a += a
total += (a*b)
else: …Run Code Online (Sandbox Code Playgroud) 我正在尝试将 Plotly 条形图 x 轴格式设置为带有 3 位小数的百分比。
import chart_studio.plotly as py #for plotting
import plotly.graph_objs as go
y = ['niner', 'deuce', 'checker']
x = [0.03, -0.05, 0.075]
fig = go.Figure(go.Bar(y = y, x = x,
name = 'returns',
orientation = 'h',
marker = dict(color = '#003663',
line = dict(
color = '#afafaf',
width = 1.5)
)))
fig.update_layout(
title = 'Why So Hard Plotly?',
xaxis = dict(
tickformat = '%.format.%3f',
title = 'Returns',
fixedrange = True,
hoverformat = '.3f',
showgrid = …Run Code Online (Sandbox Code Playgroud)