【问题标题】:New column based on conditions with different dataframe column基于具有不同数据框列的条件的新列
【发布时间】:2021-02-02 12:16:09
【问题描述】:

我有两个数据集

df1 = pd.DataFrame({"skuid" :["A","B","C","D","E"], "price": [0,0,0,0,0]})
df2 = pd.DataFrame({"skuid" :["A","B","C","D"],"salesprice" :[10,0,np.nan,30],"regularprice" : [9,10,0,2]})

我想在价格中插入销售价格和正常价格,条件如下: 如果 df1 skuid 和 df2 skuid 匹配且 df2 salesprice 不为零,则使用 salesprice 作为价格值。如果 sku 的匹配且 df2 salesprice 为零,则使用常规价格。如果不使用零作为价格值。

def pric(df1,df2):
    if (df1['skuid'] == df2['skuid'] and salesprice !=0): 
        price = salesprice 
    elif (df1['skuid'] == df2['skuid'] and regularprice !=0):
        price = regularprice
    else:
        price = 0

我做了一个类似条件的函数,但它不起作用。结果应该类似于 df1

skuid  price
  A      10
  B      10
  C      0
  D      30
  E      0

谢谢。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以使用merge,但首先使用.loc 将salesprice 值更改为等于0 的regularprice 值。最后使用 `.fillna(0) 来满足剩余条件:

    df1 = pd.DataFrame({"skuid" :["A","B","C","D","E"], "price": [0,0,0,0,0]})
    df2 = pd.DataFrame({"skuid" :["A","B","C","D"],"salesprice" :[10,0,np.nan,30],"regularprice" : [9,10,0,2]})
    df = df2.copy()
    df.loc[df['salesprice'] == 0, 'salesprice'] = df['regularprice']
    df = pd.merge(df1[['skuid']],
                  df[['skuid','salesprice']].rename({'salesprice':'price'}, axis=1),
                  how='left', on='skuid').fillna(0)
    df
    Out[1]: 
      skuid  price
    0     A   10.0
    1     B   10.0
    2     C    0.0
    3     D   30.0
    4     E    0.0
    

    【讨论】:

      【解决方案2】:

      您可以使用df.merge 和np.select:

      In [1228]: import numpy as np
      
      In [1229]: res = df1.merge(df2, on='skuid', how='outer')
      
      In [1230]: conditions = [(res.salesprice.notna() & res.regularprice.notna()) & res.salesprice.ne(0), (res.salesprice.notna() & res.regularprice.notna()) & res.salesprice.eq(0)]    
      In [1233]: choices = [res.salesprice, res.regularprice]
      
      In [1235]: res['price'] = np.select(conditions, choices) 
      In [1238]: res.drop(['salesprice', 'regularprice'], axis=1, inplace=True)
      
      In [1239]: res
      Out[1239]: 
        skuid  price
      0     A   10.0
      1     B   10.0
      2     C    0.0
      3     D   30.0
      4     E    0.0
      

      【讨论】:

        【解决方案3】:

        谢谢大家的回答,同时我也想出了一个方法,

        我用过merge和fillna

        这是

        df = pd.merge(df1, df2, how = 'left', left_on = 'skuid', right_on = 'skuid')
        df['price'] = df['price'].fillna(['SalesPrice'])
        df['price'] = df['price'].fillna(['RegularPrice'])
        df['price'] = df['price'].fillna(0)
        

        【讨论】:

        • 感谢分享。如果有帮助,请接受您认为最好的解决方案和/或投票。谢谢!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-01
        • 1970-01-01
        相关资源
        最近更新 更多