【问题标题】:Identify first non-zero element within group composed of multiple columns in pandas在熊猫中识别由多列组成的组中的第一个非零元素
【发布时间】:2018-09-01 19:33:54
【问题描述】:

我有一个如下所示的数据框。最右边的列是我想要的列:

Group1  Group2  Value   Target_Column
1        3         0      0
1        3         1      1
1        4         1      1
1        4         1      0
2        5         5      5
2        5         1      0
2        6         0      0
2        6         1      1
2        6         9      0

如何识别由两列(Group1 & Group2)组成的组中的第一个非零值,然后创建一个显示第一个非零值并将所有其他值显示为的列零?

这个问题与之前提出的问题非常相似: Identify first non-zero element within a group in pandas 但该解决方案在基于多列的组上会出错。

我试过了:

import pandas as pd
dt = pd.DataFrame({'Group1': [1,1,1,1,2,2,2,2,2], 'Group2': [3,3,4,4,5,5,6,6,6],  'Value': [0,1,1,1,5,1,0,1,9]})
dt['Newcol']=0
dt.loc[dt.Value.ne(0).groupby(dt['Group1','Group2']).idxmax(),'Newcol']=dt.Value

【问题讨论】:

  • 为什么有些组有多个1?
  • @user3483203 谢谢你的收看,我编辑了。

标签: python python-3.x pandas numpy


【解决方案1】:

设置

df['flag'] = df.Value.ne(0)

使用numpy.where 和assign:

df.assign(
    target=np.where(df.index.isin(df.groupby(['Group1', 'Group2']).flag.idxmax()),
    df.Value, 0)
).drop('flag', 1)

使用loc 和assign

df.assign(
    target=df.loc[df.groupby(['Group1', 'Group2']).flag.idxmax(), 'Value']
).fillna(0).astype(int).drop('flag', 1)

两者都产生:

   Group1  Group2  Value  target
0       1       3      0       0
1       1       3      1       1
2       1       4      1       1
3       1       4      1       0
4       2       5      5       5
5       2       5      1       0
6       2       6      0       0
7       2       6      1       1
8       2       6      9       0

【讨论】:

  • 感谢您的解决方案。我的目标是找到第一次出现的非零元素,而 idxmax 找到最大值的索引。我又添加了一行以更好地说明这一点。即使 9 是最大值,第一个非零元素 1 也会出现在它之前。
  • @gibbz00 我添加了一个额外的设置步骤,您可以在其中创建一个flag 列。尝试一下,然后尝试我的方法
【解决方案2】:

数字可能会关闭,因为当只有两个相同的值时,我不知道你需要哪一个。

使用 user3483203 的设置

df['flag'] = df.Value.ne(0)

df['Target']=df.sort_values(['flag'],ascending=False).drop_duplicates(['Group1','Group2']).Value

df['Target'].fillna(0,inplace=True)
df
Out[20]: 
   Group1  Group2  Value  Target_Column  Target
0       1       3      0              0     0.0
1       1       3      1              1     1.0
2       1       4      1              1     1.0
3       1       4      1              0     0.0
4       2       5      5              5     5.0
5       2       5      1              0     0.0
6       2       6      0              0     0.0
7       2       6      1              1     1.0

【讨论】:

  • 感谢您的解决方案。我的目标是找到第一次出现的非零元素。我又添加了一行以更好地说明这一点。即使 9 是最大值,第一个非零元素 1 也会出现在它之前。因此,该行的df.Value 为 1,其他所有内容为 0。
猜你喜欢
  • 1970-01-01
  • 2021-12-27
  • 2022-01-02
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
  • 2018-08-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多