python - 基于具有不同数据框列的条件的新列
问题描述
我有两个数据集
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
谢谢。
解决方案
您可以使用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
推荐阅读
- azure - 转换后托管磁盘在哪里?
- robotics - 单传感器测量后生成概率密度
- pandas - 重新采样数据框后如何删除不需要的列
- mysql - 从两个 DB 表中选择输出到一个输出
- java - 获取范围内wifi路由器的mac地址
- java - 如何停止 JMH 基准测试?
- php - 动态任务调度器 - Laravel
- wpf - 在 XAML 中的 DrawingBrush 中旋转渐变
- python - 在 scikit-learn 版本 0.21.2 的 OneHotEncoder 中使用 active_features_ 和 feature_indices_
- wordpress - 更改运输方式后 Woocommerce 结帐页面重新加载