首页 > 解决方案 > 基于具有不同数据框列的条件的新列

问题描述

我有两个数据集

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

谢谢。

标签: pythonpandasdataframe

解决方案


您可以使用merge,但首先使用.loc将 salesprice 值更改为等于零的常规价格值。最后使用 `.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

推荐阅读