python - Pandas:通过比较 2 个不同数据框中的 2 列来创建新列

标签 python pandas dataframe

我在 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/

相关文章:

python - 如何在字符串中包含\作为正则表达式 python 的模式

python - 计算 DataFrame 中各组的差异和均值

r - 如何使用 igraph 包从数据框中构建图表?

python - 如何在同一个 Pandas DataFrame 中切换列值

pandas - pd.dataframe.apply() 创建多个新列

python - pd.melt() 字典/一系列数据帧

python - PyQt : How to expand all children in a QTreeWidget

python - 根据其他行的某些条件获取 pandas 行的内容

python 已弃用 pd.convert_objects(convert_numeric=True) 有效,替代方案出现故障

python - 将 Pandas DataFrame 转换为多维 ndarray