【问题标题】:Compare one column against two other columns and assign the result back to the DataFrame将一列与其他两列进行比较,并将结果分配回 DataFrame
【发布时间】:2019-06-16 02:52:59
【问题描述】:

在代码下方打印

import pandas as pd

df = pd.DataFrame()

df['A'] = (10,20,34,13,45,2,34,1,18,19,23,9,40,33,17,6,15)

df['B'] = (14,26,23,41,12,24,31,1,9,53,4,22,16,19,16,28,13)

print(df)

  1. 如果 A 列中的每个数字都大于下面 5 行的数字,我想添加一个返回“TRUE”或“FALSE”的列。显然最后 4 个数字无法比较,因此可以将其视为“IGNORE”

  2. 我想添加第二列,如果 A 列中的每个数字大于 B 列下面 5 行的数字,则返回“TRUE”或“FALSE”。显然最后 4 个数字不能比较,因此这些也可以视为“忽略”

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以通过np.where查看

    s=np.where(df.A.shift(-5).isna(),'ignore',df.A>df.A.shift(-5))
    s
    Out[90]: 
    array(['True', 'False', 'True', 'False', 'True', 'False', 'True', 'False',
           'False', 'True', 'True', 'False', 'ignore', 'ignore', 'ignore',
           'ignore', 'ignore'], dtype='<U6'
    
    t=np.where(df.B.shift(-5).isna(),'ignore',df.A>df.B.shift(-5))
    
    df['col1'],df['col2']=s,t
    

    或者正如 cs95 提到的,我们可以通过使用掩码来做到这一点,并且只应用一次条件。

    s=df.shift(-5).ge(df.A,0).mask(df.A.shift(-5).isna(),'ignore')
    s.columns=['col1','col2']
    df=pd.concat([df,s],axis=1)
    

    【讨论】:

    • 感谢您的回复,它非常好,但是 cs95 响应输出 'TRUE' 或 'FALSE' 作为字符串,我可以轻松更改为 'BUY'/'SELL'。也许我可以在你的回答中,但我不知道如何。我也不应该使用真/假作为我想要的输出,因为我可能会让你感到困惑。谢谢
    【解决方案2】:

    您可以使用shift 将“A”和“B”向上移动 5 行,然后将每个移动的值与“A”进行比较。

    # shift up rows
    s = df[['A', 'B']].shift(-5)
    
    # compare against "A" and mask NaNs 
    m = s.lt(df['A'], axis=0).mask(s.isna())  
    
    # create and concatenate the result
    df2 = pd.DataFrame(
            np.select([m == 1, m == 0], ['TRUE', 'FALSE'], default='IGNORE'),
            columns=['C', 'D'],   
            index=df.index)    
    pd.concat([df, df2], axis=1)
    
         A   B       C       D
    0   10  14    TRUE   FALSE
    1   20  26   FALSE   FALSE
    2   34  23    TRUE    TRUE
    3   13  41   FALSE    TRUE
    4   45  12    TRUE   FALSE
    5    2  24   FALSE   FALSE
    6   34  31    TRUE    TRUE
    7    1   1   FALSE   FALSE
    8   18   9   FALSE   FALSE
    9   19  53    TRUE    TRUE
    10  23   4    TRUE   FALSE
    11   9  22   FALSE   FALSE
    12  40  16  IGNORE  IGNORE
    13  33  19  IGNORE  IGNORE
    14  17  16  IGNORE  IGNORE
    15   6  28  IGNORE  IGNORE
    16  15  13  IGNORE  IGNORE
    

    【讨论】:

    • 感谢您的回复,这正是我想要的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多