Pandas ValueError: Length of values does not match length of index- creating a new column

Pandas ValueError: Length of values does not match length of index- creating a new column

思路是制作股票分析图。当我尝试在 pandas 数据框中创建列 "Middle" 时出现错误。我希望该列包含开盘价和收盘价的平均值。数据源是 iex

源代码 :

from pandas_datareader import data
import pandas
import datetime
start=datetime.datetime(2018,4,1)
end=datetime.datetime(2018,4,12)
df=data.DataReader(name="AAPL",data_source="iex",start=start,end=end)

def inc_dec (c,o):
    if c>o:
        value="Increase"
    elif c<o:
        value="Decrease"
    else:
        value ="Equal"
    return value
df["status"]=[inc_dec(c,o) for c,o in zip(df.close,df.open)]

df["Middle"]=[(df.open+df.close)/2,2]

p=figure(plot_width=1000,plot_height=500,x_axis_type='datetime')
p.title.text="Cadlesticks Chart"
p.xaxis.axis_label="TIME"

hours=60*60*100

p.rect(df.index[df.status=="Decrease"],(df.open+df.close)/2,hours,abs(df.open-df.close),
      fill_color="Red",line_color="black")
p.rect(df.index[df.status=="Increase"],round((df.open+df.close)/2,2),hours,abs(df.open-df.close),
      fill_color="green",line_color="black")
p.rect(df.index[df.status=="Equal"],round((df.open+df.close)/2,2),hours,abs(df.open-df.close),
      fill_color="green",line_color="black")


output_file("Stock_analysis.html")
show(p)

输出和错误:

1y
---------------------------------------------------------------------------

ValueError: 值的长度与索引的长度不匹配

试试这个代码:你应该导入 numpy 并复制 df['Middle'] 代码。

from pandas_datareader import data
import numpy as np
import pandas
import datetime
start=datetime.datetime(2018,4,1)
end=datetime.datetime(2018,4,12)

df=data.DataReader(name="AAPL",data_source="iex",start=start,end=end)
def inc_dec (c,o):
  if c>o:
    value="Increase"
  elif c<o:
    value="Decrease"
  else:
    value ="Equal"
  return value
df["status"]=[inc_dec(c,o) for c,o in zip(df.close,df.open)]

df["Middle"]=round(np.mean(df.open+df.close), 2)