为了账号安全,请及时绑定邮箱和手机立即绑定

找到一列的重复行,然后添加其他列的对应行

找到一列的重复行,然后添加其他列的对应行

ABOUTYOU 2021-07-23 18:05:09
我想检查一列的重复行并添加其他列的相应行。如果日期框架如下: A     B         C         D  E  F  G  13348  xyzqr     324580    1  1  1  113348  grpret    325810    4  4  4  445832  gberthh   258729    2  1  3  445832  bhdrffe   025892    2  1  1  458712  bgrtw     984562    2  2  2  276493  hzrt      638495    1  1  1  2643509 .         T648501   1  1  1  1643509 .         R648501   1  1  1  1之后,添加列(B、C、D、E、F)的对应行必须检查对应行的所有列是否相等。如果相等,则为其他列提供相同的数字,否则为“0”。对于上面的示例,由于 13348 有两个重复行,并且相应行的添加为 (D=5, E=5, F=5, G=5) 的每一列提供了 5,因此输出应为 5。而, 因为 45832 相加后有不同的列 (D=4, E=2, F=4, G=8) 值,所以输出应该是 0。剩余的列应该是重复行的最小索引值。输出应如下所示:   A     B       C       D   13348  xyzqr   324580  5  45832  gberthh 258729  0  58712  bgrtw   984562  2  76493  hzrt    638495  0  643509 .       T648501 2我很高兴知道一些建议。
查看完整描述

1 回答

?
MM们

TA贡献1886条经验 获得超2个赞

我认为需要:


cols = ['D','E','F','G']

#for each group transpose df and check if all duplicates

df1 = df.groupby('A')[cols].apply(lambda x: x.T.duplicated(keep=False))

#for duplicates aggregate sum else 0

arr = np.where(df1.all(axis=1), df.groupby('A')[cols[0]].sum(), 0)

#remove unnecessary columns and add new, get first rows per column A

df = df.drop(cols, axis=1).drop_duplicates('A').assign(D=arr)

print (df)

        A        B        C  D

0   13348    xyzqr   324580  5

2   45832  gberthh   258729  0

4   58712    bgrtw   984562  2

5   76493     hzrt   638495  0

6  643509        .  T648501  2

如果所有值都是重复的,则检查每个组的替代解决方案:


cols = ['D','E','F','G']

m = df.groupby('A')[cols].apply(lambda x: x.T.duplicated(keep=False).all())

print (m)

A

13348     True

45832    False

dtype: bool


arr = np.where(m, df.groupby('A')[cols[0]].sum(), 0)

df = df.drop(cols, axis=1).drop_duplicates('A').assign(D=arr)

print (df)

        A        B        C  D

0   13348    xyzqr   324580  5

2   45832  gberthh   258729  0

4   58712    bgrtw   984562  2

5   76493     hzrt   638495  0

6  643509        .  T648501  2


查看完整回答
反对 回复 2021-07-28
  • 1 回答
  • 0 关注
  • 118 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信