【问题标题】:Intersection of rows of a Dataframe based on the value in a column in the dataframe基于数据框中列中的值的数据框行的交集
【发布时间】:2020-06-08 15:02:40
【问题描述】:

我有一个 df,如下所示。我正在尝试根据主机列的值查找行的交集。

host    values 
test    ['A','B','C','D']
test    ['D','E','B','F']
prod    ['1','2','A','D','E']
prod    []
prod    ['2']

预期输出是第一行与下一行的交集 如果主机值相同。 对于上面的 df,输出将是

test=['B','D'] - intersection of row 1 and 2
prod=[] - intersection of row 3 and 4
prod=[] - intersection of row 4 and 5

由于主机列值不匹配,不执行第 2 行和第 3 行的交集。任何帮助表示赞赏。

df.to_dict() 值为

 {'host': {0: 'test', 1: 'test', 2: 'prod', 3: 'prod', 4: 'prod'},
 'values': {0: ['A', 'B', 'C', 'D'],
  1: ['D', 'E', 'B', 'F'],
  2: ['1', '2', 'A', 'D', 'E'],
  3: [],
  4: ['2']}
 }

【问题讨论】:

    标签: python python-3.x pandas dataframe intersection


    【解决方案1】:

    不确定预期结果的结构,但您可以使用shift为每组主机创建一个列。然后使用apply,其中这个新列是notna,并做sets的交集。

    df['val_shift'] = df.groupby('host')['values'].shift()
    df['intersect'] = df[df['val_shift'].notna()]\
                        .apply(lambda x: list(set(x['values'])&set(x['val_shift'])), axis=1)
    print (df)
       host           values        val_shift intersect
    0  test     [A, B, C, D]              NaN       NaN
    1  test     [D, E, B, F]     [A, B, C, D]    [B, D]
    2  host  [1, 2, A, D, E]              NaN       NaN
    3  host               []  [1, 2, A, D, E]        []
    4  host              [2]               []        []
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-21
      • 2013-02-20
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多