【问题标题】:How to find combinations between values of two columns in Pandas?如何在 Pandas 中查找两列值之间的组合?
【发布时间】:2023-04-08 19:32:01
【问题描述】:

我的数据框如下所示:

Source  Target  Value  Source location  Target location
a       b       10     [12.3,1.9]       [13.5,14.3]
c       v       10     [15.3,1.9]       [13.5,94.3]
c       d       18     [1.4,31.9]       [16.6,44.7]
p       q       10     [12.3,1.9]       [13.5,15.3]
x       z        8     [6.3,1.4]        [47.5,4.3]

我想找到SourceTarget 之间的两个配对。我希望我的最终结果如下所示:

Source  Target  Value  Source location  Target location
a       b       10     [12.3,1.9]       [13.5,14.3]
b       a        9     [72.9,18.6]       [14.2,31.6]
c       e       18     [1.4,31.9]       [16.6,44.7]
e       c       14     [19.4,5.1]       [12.3,23.4]
z       x        6     [92.3,1.9]       [43.5,14.3]
x       z        8     [6.3,1.4]        [47.5,4.3]

如您所见,我想同时获得 SourceTarget 对 - 即 a-cc-a 作为两行。

我尝试对 Stackoverflow 进行研究,但似乎这个问题之前没有得到解答。我查看了thisthis,但他们使用groupby 来查找未重新排列现有数据框的列数。 This 一个是我得到的最接近的,但它返回行而不是列的唯一组合的数据帧。 任何帮助将不胜感激。

【问题讨论】:

    标签: python pandas combinations


    【解决方案1】:

    一种可能的解决方案是:

    定义一个即将应用的函数:

    def fn(row):
        r2 = row.copy()
        r2.Source, r2.Target = r2.Target, r2.Source
        r2['Source location'], r2['Target location'] =\
            r2['Target location'], r2['Source location']
        return r2
    

    然后运行:

    pd.concat([df, df.apply(fn, axis=1)]).sort_index()
    

    这条指令:

    • fn 函数应用于 df,产生一个“影子”数据帧 带有“对反转”列
      • 来源目标
      • 源位置目标位置
    • 连接它们。
    • 按索引排序。

    如果您对“双倍”索引值不满意,请添加.reset_index(drop=True)

    【讨论】:

      猜你喜欢
      • 2017-04-04
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-18
      • 2021-12-02
      相关资源
      最近更新 更多