我可能会从nodes.Label 和nodes.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
一些解释。首先,我们从 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 上工作,因为它适用于行和列,而不是元素。但是我们可以stack 和unstack 来解决这个问题:
>>> 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
或者,我们也可以只使用lambda 和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 的相同方法将起作用,但您必须限制应用程序。例如,如果您想换一种方式,您可能不希望权重列中的2 变为fou。