【问题标题】:Pandas groupby two columns and count shared values in thirdPandas 按两列分组并在第三列中计算共享值
【发布时间】:2021-11-23 21:24:14
【问题描述】:

在 Pandas 中,我想按两列分组并计算共享了多少第三列值。增加了对更多共享的偏好。

在下面的数据框中,将 col1 值分组,将 col2 值分组并计算 col2 值共享 col3 值的频率。

结果是:ID1 和 ID2 共享一个 col3 值 (2)。 ID3 与无共享 (1)。但是,ID1、ID2 和 ID4 也共享一个值 (3)。由于 ID1 和 ID2 已经共享一个值,因此采用两个 ID 共享的值和更多 (3)。因此答案是 3,1。计数列表必须始终 = 唯一的 col2 值。

col1 col2 col3
A ID1 15
A ID1 16
A ID1 12
A ID2 15
A ID2 12
A ID3 18
A ID4 19
A ID4 12

【问题讨论】:

  • 你能提供你实际想要的结果吗?不仅仅是对中间结果的解释
  • @SangeerththanBalachandran - 我拒绝了您的编辑,因为您可以使用pd.read_html('https://stackoverflow.com/q/69419264/14277722')[0] 将此表读入数据框。您的修改让事情变得更加困难。
  • 感谢您的反馈!答案很简单(对于 A):A:3,1。它可以是 dict 或 df ,其中第二列是列表,没关系。实际上,第一列中会有 B、C 等,所以进一步的结果

标签: python pandas numpy


【解决方案1】:

如果我对您的理解正确,我认为您希望按 col3 而不是 col2 分组:

df = pd.read_html('https://stackoverflow.com/q/69419264/14277722')[0]

df = df.groupby(['col1','col3'])['col2'].apply(list).reset_index()
df['count'] = df['col2'].apply(len)

然后,您可以删除 col2 是另一行的子集的行 the following:

arr = pd.get_dummies(df['col2'].explode()).max(level=0).to_numpy()
subsets = np.matmul(arr, arr.T)
np.fill_diagonal(subsets, 0)
mask = ~np.equal(subsets, np.sum(arr, 1)).any(0)

df = df[mask]
   col1 col3             col2  count
0     A   12  [ID1, ID2, ID4]      3
3     A   18            [ID3]      1     

【讨论】:

  • col2 中的重复列表应该首先被删除:#Convert to hashable type df['gID'] = df['col2'].astype(str) #Drop duplicates df = df.groupby(' col2_str').apply(lambda x: x.sample(1)).reset_index(drop=True) df = df.drop(['col2_str'], axis=1)
猜你喜欢
  • 2022-07-06
  • 2018-11-29
  • 2022-11-12
  • 1970-01-01
  • 2019-01-13
  • 1970-01-01
  • 1970-01-01
  • 2017-02-22
  • 2021-12-04
相关资源
最近更新 更多