【问题标题】:Pandas Dataframes - Populating df2 based on criteria in df1Pandas Dataframes - 根据 df1 中的标准填充 df2
【发布时间】:2017-11-18 23:30:01
【问题描述】:

我有这个数据帧 (df1),我想根据它将数据输入另一个数据帧 (df2)。如果 df1 的值大于 54,我希望 df2 中的同一行在“Buy”列下为“Buy”,如果不是,我希望它在“sell”列下为“Sell”。我知道这听起来很简单,但由于某种原因,当我使用下面的代码执行此操作时,它会根据 df1 中的最后一个值设置 df2 中的所有值。

for x in df1['A']:
    if x > 54:
       df2['Buy'] = "Buy"

    else:
       df2['Sell'] = "Sell"

df1:

    Date
    2011-08-26     53.024284
    2011-08-29     55.454285
    2011-08-30     55.464287
    2011-08-31     55.795715
    2011-09-01     55.117142
    2011-09-02     53.534286

df2:

            Buy  Hold  Sell
Date
2011-08-26  0.0    0.0   0.0
2011-08-29  0.0    0.0   0.0
2011-08-30  0.0    0.0   0.0
2011-08-31  0.0    0.0   0.0
2011-09-01  0.0    0.0   0.0
2011-09-02  0.0    0.0   0.0

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    首先需要两个索引相同,然后可以在另一个 DataFrame df2 中使用由 df1 中的条件创建的布尔掩码:

    m = df1['A'] > 54
    df2['Buy'] = df2['Buy'].mask(m, "Buy")
    df2['Sell'] = df2['Sell'].mask(~m, "Sell")
    

    assign:

    df2 = df2.assign(Buy= df2['Buy'].mask(m, "Buy"),Sell = df2['Sell'].mask(~m, "Sell"))
    

    或者:

    df2.loc[m, 'Buy'] = "Buy"
    df2.loc[~m, 'Sell'] = "Sell"
    

    print (df2)
                Buy  Hold  Sell
    Date                       
    2011-08-26    0   0.0  Sell
    2011-08-29  Buy   0.0     0
    2011-08-30  Buy   0.0     0
    2011-08-31  Buy   0.0     0
    2011-09-01  Buy   0.0     0
    2011-09-02    0   0.0  Sell
    

    如果索引不同,请使用reindex:

    m = (df1['A'] > 54).reindex(df2.index, fill_value=False)
    

    【讨论】:

    • 先生,您通过重新索引得到了我。会记住这个的。我第一次看到在面具上重新索引:)
    【解决方案2】:

    使用np.where,即

    df2['Buy'] = np.where(df1['A']>54,'Buy',df2['Buy'])
    df2['Sell'] = np.where(df1['A']<54,'Sell',df2['Sell'])
    

    df.where

    df2['Buy'] = df2['Buy'].where(df1['A']<54,'Buy')
    df2['Sell'] = df2['Sell'].where(df1['A']>54,'Sell')
    

    输出:

    买入 持有 卖出 日期 2011-08-26 0.0 0.0 卖出 2011-08-29 买入 0.0 0.0 2011-08-30 买入 0.0 0.0 2011-08-31 买入 0.0 0.0 2011-09-01 购买 0.0 0.0 2011-09-02 0.0 0.0 卖出

    如果索引不同,那么您必须按照@jezrael 在他的解决方案中的建议进行重新索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-04
      • 2021-04-07
      • 2018-08-06
      • 2020-09-26
      相关资源
      最近更新 更多