我有一个如下所示的数据框。最右边的一列是我想要的列:
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
最佳答案
设置
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/