python - 如何根据列值乘以 2 个不相等的数据帧?
问题描述
我有 2 个数据框。如何根据特定列将 2 个不相等的数据帧相乘。是否有任何 pandas 包或者我需要使用循环。有人可以分享将 2 个不等维度的数据帧相乘的代码。
df1 is below:
features tf_vals
0 this 0.200000
1 is 0.200000
2 the 0.200000
3 first 0.200000
4 document 0.200000
5 this 0.166667
6 document 0.333333
7 is 0.166667
8 the 0.166667
9 second 0.166667
10 and 0.166667
11 this 0.166667
df2 is :
features idf_vals
0 the 1.000000
1 this 1.000000
2 document 1.000000
3 is 1.000000
4 first 1.510826
5 one 1.916291
6 second 1.916291
7 and 1.916291
8 third 1.916291
How do I multiply df1 and df2 based on column name 'features'.
Desired output:
I want to multiply value of word in df1 and value of word in df2. example(value of word 'this' in df1 * value of word 'this' in df2 )
features Mult
this 0.2
is 0.2
the 0.2
first 0.3021652
document 0.2
this 0.166667
document 0.333333
is 0.166667
the 0.166667
second 0.319382472
and 0.319382472
this 0.166667
解决方案
想法是使用Series.map
bydf1['features']
然后使用 multibySeries.mul
来避免对features
列进行排序:
s = df2.set_index('features')['idf_vals']
df1['Mult'] = df1['features'].map(s).mul(df1.pop('tf_vals'))
print (df1)
features Mult
0 this 0.200000
1 is 0.200000
2 the 0.200000
3 first 0.302165
4 document 0.200000
5 this 0.166667
6 document 0.333333
7 is 0.166667
8 the 0.166667
9 second 0.319382
10 and 0.319382
11 this 0.166667
推荐阅读
- python - 如何将每个配对值作为单独的列表 |python|
- javascript - Redux-saga 调用多个动作/函数以进行调度
- vue.js - 如何将 socket.io-client 导入每个组件?
- c# - Autofac中基于Environment的不同DI实现
- javascript - 如何在 socket express.js 中使用 req 和 res
- javascript - 如何创建动态组件
- powerapps - 如何将变量从 PowerApp 传递到 PowerApp 流的 HTTP 步骤?
- python - 异步例程中的 For 循环不更新循环变量。如何使画布坐标异步实时?
- angular - 角度 *ngIf
- hyperledger-fabric - 频道创建失败:仅满足 0 个策略,但需要 [ OrdererOrg/Writers ] 中的 1 个