Skip to main content
 首页 » 编程设计

python之根据其他数据框python中的值有条件地在数据框中添加一列

2024年10月17日8arxive

我在 pandas df 中有一张 table

id   product_1 count 
1        100     10 
2        200     20 
3        100     30 
4        400     40 
5        500     50 
6        200     60 
7        100     70 

我在数据框 df2 中还有另一个表

product    score 
100         5 
200         10 
300         15 
400         20 
500         25 
600         30 
700         35 

我必须在我的第一个 df 中创建一个新列 score,从 df2 中获取关于 product_1 的得分值。

我的最终输出应该是。 df =

id   product_1 count  score 
1        100     10     5 
2        200     20     10 
3        100     30     5 
4        400     40     20 
5        500     50     25 
6        200     60     10 
7        100     70     5 

有什么实现方法吗?

请您参考如下方法:

使用map :

df['score'] = df['product_1'].map(df2.set_index('product')['score'].to_dict()) 
print (df) 
   id  product_1  count  score 
0   1        100     10      5 
1   2        200     20     10 
2   3        100     30      5 
3   4        400     40     20 
4   5        500     50     25 
5   6        200     60     10 
6   7        100     70      5 

或merge :

df = pd.merge(df,df2, left_on='product_1', right_on='product', how='left') 
print (df) 
   id  product_1  count  product  score 
0   1        100     10      100      5 
1   2        200     20      200     10 
2   3        100     30      100      5 
3   4        400     40      400     20 
4   5        500     50      500     25 
5   6        200     60      200     10 
6   7        100     70      100      5 

通过评论编辑:

df['score'] = df['product_1'].map(df2.set_index('product')['score'].to_dict()) 
df['final_score'] = (df['count'].mul(0.6).div(df.id)).add(df.score.mul(0.4)) 
print (df) 
   id  product_1  count  score  final_score 
0   1        100     10      5          8.0 
1   2        200     20     10         10.0 
2   3        100     30      5          8.0 
3   4        400     40     20         14.0 
4   5        500     50     25         16.0 
5   6        200     60     10         10.0 
6   7        100     70      5          8.0