python - 在 Pandas 数据框中按递增顺序重新排序节点

标签 python pandas dataframe

data1 = { 'node1': [2,2,3,6],
     'node2': [6,7,7,28],
     'weight': [1,2,1,1], }
df1 = pd.DataFrame(data1, columns = ['node1','node2','weight'])

我想按升序重命名data1中的node1和node 2。 节点是 2 3 6 7 28 所以它们分别变成 1 2 3 4 5。

所以数据框变成了-

data1 = { 'node1': [1,1,2,3],
     'node2': [3,4,4,5],
     'weight': [1,2,1,1], }
df1 = pd.DataFrame(data1, columns = ['node1','node2','weight'])

之前的数据是这样的

enter image description here

但现在看起来是这样的

enter image description here

最佳答案

通过 reshape 排序和赋值进行因式分解,即

df1[['node1','node2']] = (pd.factorize(np.sort(df1[['node1','node2']].values.reshape(-1)))[0]+1).reshape(-1,len(df1)).T

    node1  node2  weight
0      1      3       1
1      1      4       2
2      2      4       1
3      3      5       1

另一种使用 dict 进行 melt 和 factorize 并重命名的方法

vals = pd.factorize(df1[['node1','node2']].melt().sort_values('value')['value'])

to_rename = dict(zip(vals[1],np.unique(vals[0]+1)))
# {2: 1, 3: 2, 6: 3, 7: 4, 28: 5}

df1[['node1','node2']] = df1[['node1','node2']].apply(lambda x : x.map(to_rename))
# Also df1[['node1','node2']] = df1[['node1','node2']].replace(to_rename) Thanks @jezrael

  node1  node2  weight
0      1      3       1
1      1      4       2
2      2      4       1
3      3      5       1

关于python - 在 Pandas 数据框中按递增顺序重新排序节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47635397/

相关文章:

python - 是否可以在一个文件中写入和读取多个 DataFrame?

python - 比较两个不同大小的数据框中的每个元素并在 Pandas 中添加或删除单词

python - 导入错误: No module named 'cloudant.client' ; 'cloudant' is not a package

python - 倒排索引是如何存储的?

python - 导入错误 : No module named 'botocore.parameters'

python - 在 Pandas 中添加大小不均的数据列

python - 按条件将值广播到数据帧组

Python:for循环迭代通过对象,而不是字符串

python - pandas 使用 groupby 填充

python - 在 Python 列表中查找元素的有效方法?