python - 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())
我正在尝试通过实践来理解理论、库和方法,如果太明显的话,请耐心等待... :]
解决方案
该where
方法总是从数据帧中调用,但是在这里,您只需要检查系列的条件,所以我找到了两种解决此问题的方法:
- 新
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.
- 或者你可以直接检查条件如下:
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
推荐阅读
- python - 如何使用 python 将包含超链接 .docx 的文档合并到另一个 .docx?
- javascript - 如何将下面的 JS 代码转换为 ES6 类代码
- html - 怎么把图标放进去
- 标签?
- flutter - 缩小的 ListView 被截断
- c# - 如何使用 json.net 序列化和反序列化多态列表,同时保留继承的对象类型?
- cadence-workflow - Cadence 中有哪些不同的服务以及历史服务如何作为核心工作流引擎工作?
- apache-superset - 预设 Apache Superset Starter Plan,是否可以嵌入公共仪表板
- javascript - javascript如何过滤多个条件的数组
- php - 目标类 [Facade\Ignition\Middleware\AddJobInformation] 不存在
- reactjs - 排除这个 useEffect 依赖数组变量是否明智?lint 推荐 3,但我只想依赖 1