gpt4 book ai didi

python - 使用 Pandas 将名称替换为单独文件中的索引

转载 作者:行者123 更新时间:2023-11-30 23:36:52 25 4
gpt4 key购买 nike

我有一个节点和一个边缘列表,如下所示:

Id   Label   Type
1 fie gnome
2 fou giant
3 fim gnome
4 fee dwarf

Source target Weight
fie fou 2
fie fim 2
fou fee 2
fee fim 3

如何用节点文件中的索引替换源文件和目标文件中的名称?

最终输出应该是:

Source target   Weight
1 2 2
1 3 2
2 4 2
4 3 3

最佳答案

我可能会从 nodes.Labelnodes.Id 构建一个 dict,然后将其传递给 replace( )applymap。例如:

>>> weight.stack().replace(dict(zip(nodes.Label, nodes.Id))).unstack()
Source target Weight
0 1 2 2
1 1 3 2
2 2 4 2
3 4 3 3
>>> d = dict(zip(nodes.Label, nodes.Id))
>>> weight.applymap(lambda x: d.get(x,x))
Source target Weight
0 1 2 2
1 1 3 2
2 2 4 2
3 4 3 3
<小时/>

一些解释。首先,我们从 DataFrame 开始:

>>> nodes
Id Label Type
0 1 fie gnome
1 2 fou giant
2 3 fim gnome
3 4 fee dwarf
>>> weight
Source target Weight
0 fie fou 2
1 fie fim 2
2 fou fee 2
3 fee fim 3

然后我们制作我们想要替换的dict:

>>> d = dict(zip(nodes.Label, nodes.Id))
>>> d
{'fou': 2, 'fim': 3, 'fee': 4, 'fie': 1}

不幸的是,.replace() 并不像您想象的那样在 DataFrame 上工作,因为它适用于行和列,而不是元素。但我们可以stackunstack来解决这个问题:

>>> weight.stack()
0 Source fie
target fou
Weight 2
1 Source fie
target fim
Weight 2
2 Source fou
target fee
Weight 2
3 Source fee
target fim
Weight 3
dtype: object
>>> weight.stack().replace(d)
0 Source 1
target 2
Weight 2
1 Source 1
target 3
Weight 2
2 Source 2
target 4
Weight 2
3 Source 4
target 3
Weight 3
dtype: object
>>> weight.stack().replace(d).unstack()
Source target Weight
0 1 2 2
1 1 3 2
2 2 4 2
3 4 3 3

或者,我们也可以只使用 lambdaapplymap。字典有一个接受默认参数的 get 方法,因此 somedict.get(k, 'default value gets here') 将查找键 k up,如果找到key则返回对应的值,否则返回第二个参数。因此,d.get(x, x) 会将 x 更改为字典中的相应值,或者返回 x 并保留它。因此:

>>> weight.applymap(lambda x: d.get(x,x))
Source target Weight
0 1 2 2
1 1 3 2
2 2 4 2
3 4 3 3

PS:如果您只想将替换应用于某些列,则相同的基于字典的方法也可以使用,但您必须限制应用程序。例如,如果您想采用其他方式,您可能不希望权重列中的 2 变为 fou

关于python - 使用 Pandas 将名称替换为单独文件中的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16108423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com