python - 识别 pandas 中由多列组成的组中的第一个非零元素

标签 python python-3.x pandas numpy

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

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

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

这个问题与之前提出的问题非常相似: 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

最佳答案

设置

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

使用numpy.where分配:

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

使用loc分配

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

关于python - 识别 pandas 中由多列组成的组中的第一个非零元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52131535/

相关文章:

python - 使用 venv 时环境 $PATH 不同

python - 什么时候触发写入磁盘?

python-3.x - 在 Python 中创建 Iterable 鼠标单击事件?

python - Python中带有百分比限制的修剪平均值?

python - 读取包内的csv文件

python - 如何从 distutils 二进制发行版中剥离源代码?

python - 如何使用python打开触摸键盘?

python - 复制 Scipy 的 RegressionResults.predict 功能

python - Pandas 有某种方法可以按一列聚合行并按另一列排序吗?

python-3.x - 按 ID 分组,同时保留所有数据。 Python。 Pandas