首页 > 解决方案 > ValueError:条件数组必须与自身的形状相同

问题描述

我是熊猫的超级菜鸟,我正在学习一个显然已经过时的教程。

我有这个简单的脚本,当我运行时出现 tis 错误:

ValueError: Array conditional must be same shape as self

# loading the class data from the package pandas_datareader
import pandas as pd
from pandas_datareader import data
import matplotlib.pyplot as plt

# Adj Close:
# The closing price of the stock that adjusts the price of the stock for corporate actions.
# This price takes into account the stock splits and dividends.
# The adjusted close is the price we will use for this example.
# Indeed, since it takes into account splits and dividends, we will not need to adjust the price manually.

# First day
start_date = '2014-01-01'
# Last day
end_date = '2018-01-01'
# Call the function DataReader from the class data
goog_data = data.DataReader('GOOG', 'yahoo', start_date, end_date)

goog_data_signal = pd.DataFrame(index=goog_data.index)
goog_data_signal['price'] = goog_data['Adj Close']
goog_data_signal['daily_difference'] = goog_data_signal['price'].diff()

goog_data_signal['signal'] = 0.0
# this line produces the error
goog_data_signal['signal'] = pd.DataFrame.where(goog_data_signal['daily_difference'] > 0, 1.0, 0.0)
goog_data_signal['positions'] = goog_data_signal['signal'].diff()
print(goog_data_signal.head())

我正在尝试通过实践来理解理论、库和方法,如果太明显的话,请耐心等待... :]

标签: pythonpandasyahoo-finance

解决方案


where方法总是从数据帧中调用,但是在这里,您只需要检查系列的条件,所以我找到了两种解决此问题的方法:

  1. where方法不支持为条件为真的行设置值(在您的情况下为 1.0),但仍支持为假行设置值(称为docother中的参数)。因此,您可以稍后手动设置 1.0,如下所示:
goog_data_signal['signal'] = goog_data_signal.where(goog_data_signal['daily_difference'] > 0, other=0.0)
# the true rows will retain their values and you can set them to 1.0 as needed.
  1. 或者你可以直接检查条件如下:
goog_data_signal['signal'] = (goog_data_signal['daily_difference'] > 0).astype(int)

第二种方法为我生成输出:

price  daily_difference  signal  positions
Date                                                       
2014-01-02  554.481689               NaN       0        NaN
2014-01-03  550.436829         -4.044861       0        0.0
2014-01-06  556.573853          6.137024       1        1.0
2014-01-07  567.303589         10.729736       1        0.0
2014-01-08  568.484192          1.180603       1        0.0

推荐阅读