【问题标题】:Struggling implementing loops using array oriented programming使用面向数组的编程努力实现循环
【发布时间】:2016-05-10 00:13:12
【问题描述】:

我在处理 pandas/numpy 中的循环时遇到了麻烦。以这段代码为例

import pandas as pd

eurusd = pd.read_csv('EURUSD.csv',index_col='Date',parse_dates=True,usecols=['Date','High','Low','Open','Close'])
gbpusd = pd.read_csv('GBPUSD.csv',index_col='Date',parse_dates=True,usecols=['Date','High','Low','Open','Close'])
audusd = pd.read_csv('AUDUSD.csv',index_col='Date',parse_dates=True,usecols=['Date','High','Low','Open','Close'])


eurusd['MovingAvg'] = pd.rolling_mean(eurusd.Close,100)
gbpusd['MovingAvg'] = pd.rolling_mean(gbpusd.Close,100)
audusd['MovingAvg'] = pd.rolling_mean(audusd.Close,100)

我将如何实现显示

的逻辑
if the eurusd.Close is less than the eurusd.MovingAvg 
AND if gbpusd.Close is less than the gbpusd.MovingAvg
AND if audusd.Close is GREATER than the audusd.MovingAvg
then set some condition to TRUE

【问题讨论】:

  • if eurusd.Close < eurusd.MovingAvg and gbpusd.Close < gbpusd.MovingAvg and audusd.Close > audusd.MovingAvg
  • 返回 ValueError: Series 的真值是不明确的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
  • MovingAvg 是一组值,您必须选择一个进行比较

标签: python arrays numpy pandas


【解决方案1】:

使用股票和雅虎金融来说明这个概念:

import pandas.io.data as web

df = web.DataReader(['F', 'AAPL', 'IBM'], 'yahoo', '2015-01-02', '2016-01-01')['Adj Close']

df = pd.concat([df, 
                pd.rolling_mean(df, window=100).rename(
                    columns={col: col + "_100" for col in df})], 
               axis=1)

df['condition'] = False
df.loc[(df.F < df.F_100) & 
       (df.AAPL < df.AAPL_100) & 
       (df.IBM > df.IBM_100), 'condition'] = True

>>> df.tail()
                  AAPL          F         IBM    AAPL_100      F_100     IBM_100 condition
Date                                                                                      
2015-12-24  106.796739  13.692101  135.544053  112.421986  13.616413  140.126056     False
2015-12-28  105.600553  13.567714  134.916580  112.347147  13.611907  139.954141     False
2015-12-29  107.498633  13.615554  137.044105  112.288827  13.607596  139.806220     False
2015-12-30  106.094845  13.558146  136.612715  112.212631  13.602994  139.665642     False
2015-12-31  104.058365  13.481600  134.926379  112.074727  13.595828  139.492368     False

>>> df.condition.sum()
8

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 2021-02-06
    • 1970-01-01
    • 2014-12-01
    • 2021-09-12
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 2018-03-29
    相关资源
    最近更新 更多