识别 pandas 组中的第一个非零元素 [英] Identify first non-zero element within a group in pandas
本文介绍了识别 pandas 组中的第一个非零元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的数据框.最右边的列是我想要的列:
I have a dataframe that looks like the following. The rightmost column is my desired column:
Group Value Target_Column
1 0 0
1 0 0
1 1 1
1 2 0
2 0 0
2 1 1
2 0 0
2 1 0
如何识别组(Group
)中的第一个非零值,然后创建一个保留第一个非零值并显示所有其他零的列?
How do I identify the first non-zero value in a group(Group
) and then create a column that retains the first non-zero value and show all else as zeroes?
如解决方案中所述,我一直在尝试利用idxmax
进行此操作:
在的每个列中查找第一个非零值熊猫DataFrame
I have been trying to leverage idxmax
for this as stated in this solution:
Find first non-zero value in each column of pandas DataFrame
import pandas as pd
df = pd.DataFrame({'Group': [1,1,1,1,2,2,2,2], 'Value': [0,0,1,1,0,1,0,1]})
df.ne(0).idxmax()
g = df.groupby('Group').Value
g.ne(0).idxmax()
推荐答案
使用idxmax
df['Newcol']=0
df.loc[df.Value.ne(0).groupby(df['Group']).idxmax(),'Newcol']=1
df
Out[41]:
Group Value Target_Column Newcol
0 1 0 0 0
1 1 0 0 0
2 1 1 1 1
3 1 2 0 0
4 2 0 0 0
5 2 1 1 1
6 2 0 0 0
7 2 1 0 0
这篇关于识别 pandas 组中的第一个非零元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文