1

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

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
4

1 回答 1

3

我可能会构建一个dictfrom nodes.Labeland nodes.Id,然后将它传递给replace()或 to 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

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

>>> 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

或者,或者,我们可以只使用lambdaand applymap。字典有一个get接受默认参数的方法,因此somedict.get(k, 'default value goes here')会查找键k,如果找到键则返回相应的值,否则返回第二个参数。所以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:如果您只想将替换应用于某些列,则相同的基于 dict 的方法将起作用,但您必须限制应用程序。例如,如果您想换一种方式,您可能不希望2weight 列中的 变为fou

于 2013-04-19T16:10:47.470 回答