牧羊人nacy
决定对这个问题找点乐子。您可以将node1和转换node2为 Categorical dtype,然后使用groupby.from functools import partialvals = np.unique(df[['node1', 'node2']])p = partial(pd.Categorical, categories=vals) df['node1'], df['node2'] = p(df['node1']), p(df['node2'])(df.groupby(['node1', 'node2']) .first() .fillna(0, downcast='infer') .weight .unstack())node2 a b c dnode1 a 0 0 1 0b 0 0 2 0c 0 0 0 0d 0 0 3 0另一种选择是直接设置底层数组值。df2 = pd.DataFrame(0, index=vals, columns=vals)f = df2.index.get_indexerdf2.values[f(df.node1), f(df.node2)] = df.weight.valuesprint(df2) a b c da 0 0 1 0b 0 0 2 0c 0 0 0 0d 0 0 3 0