我在 pandas 中有 2 个数据框。
度数:
Target in_degree
0 2 1
1 4 24
2 5 53
3 6 98
4 7 34
出度
Source out_degree
0 1 4
1 2 4
2 3 5
3 4 5
4 5 5
通过比较两列,我想创建一个新的数据框,其中应添加“in_ Degree”和“out_ Degree”列并显示结果。
示例输出应如下所示
Source/Target out_degree
0 1 4
1 2 5
2 3 5
3 4 29
4 5 58
如有任何帮助,我们将不胜感激。
谢谢。
最佳答案
传统上,这需要合并,但我认为您可以利用 pandas 的索引对齐算法来更快地完成此操作。
x = df2.set_index('Source')
y = df1.set_index('Target').rename_axis('Source')
y.columns = x.columns
x.add(y.reindex(x.index), fill_value=0).reset_index()
Source out_degree
0 1 4.0
1 2 5.0
2 3 5.0
3 4 29.0
4 5 58.0
解决这个问题的“传统”SQL 方法是使用合并:
v = df1.merge(df2, left_on='Target', right_on='Source', how='right')
dct = dict(
Source=v['Source'],
out_degree=v['in_degree'].add(v['out_degree'], fill_value=0))
pd.DataFrame(dct).sort_values('Source')
Source out_degree
3 1 4.0
0 2 5.0
4 3 5.0
1 4 29.0
2 5 58.0
关于python - Pandas:通过比较 2 个不同数据框中的 2 列来创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53092789/