用python字典中的Integer值替换文本中的值,然后求和 - python

我有一个像这样的数据框:

column1 column2
   1     apple,apple,apple
   2     ball,ball,ball
   3     cat,dog,eel
   4     dog,dog,dog
   5     apple,cat,eel
   6     apple,ball,cat

我有一本对每个单词都有价值的字典:

{apple:1,
 ball:2,
 cat:3,
 dog:4,
 eel:5}

我想使用此字典替换数据框中的值,并找到每一行的总和。我怎样才能做到这一点?

最后,我想要这样的东西:

column1      column2          column3 
   1     apple,apple,apple      3
   2     ball,ball,ball         6 
   3     cat,dog,eel            12
   4     dog,dog,dog            12
   5     apple,cat,eel          9
   6     apple,ball,cat         6

参考方案

IIUC split + explode然后map

df.column2.str.split(',').explode().map(d).sum(level=0)
Out[286]: 
0     3
1     6
2    12
3    12
4     9
5     6
Name: column2, dtype: int64
df['column3']=df.column2.str.split(',').explode().map(d).sum(level=0)

python :安装 python 后,如何导入 Pandas - python

我已经安装了 python 。现在,当我尝试跑步时import pandas as pd 我收到以下错误Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import pandasFile ImportError: …

Python Pandas检查数据框是否不为空 - python

我有一个if语句,它在其中检查数据框是否为空。我的操作方式如下:if dataframe.empty: pass else: #do something 但实际上我需要:if dataframe is not empty: #do something 我的问题是-是否有一种.not_empty()方法可以实现这一目标?我还想问一下第二个版本在性能方面是否更好…

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…

Python Pandas:按分组分组,平均? - python

我有一个像这样的数据框:cluster org time 1 a 8 1 a 6 2 h 34 1 c 23 2 d 74 3 w 6 我想计算每个集群每个组织的平均时间。预期结果:cluster mean(time) 1 15 ((8+6)/2+23)/2 2 54 (74+34)/2 3 6 我不知道如何在熊猫中做到这一点,有人可以帮忙吗? 参考方案 如…

Python:图像处理可产生皱纹纸效果 - python

也许很难描述我的问题。我正在寻找Python中的算法,以在带有某些文本的白色图像上创建皱纹纸效果。我的第一个尝试是在带有文字的图像上添加一些真实的皱纹纸图像(具有透明度)。看起来不错,但副作用是文本没有真正起皱。所以我正在寻找更好的解决方案,有什么想法吗?谢谢 参考方案 除了使用透明性之外,假设您有两张相同尺寸的图像,一张在皱纹纸上明亮,一张在白色背景上有深…