我有以下数据框:
'one_hot'
1 0
2 1
3 0
4 0
5 0
6 1
我想知道是否有一个函数可以让我对剩下的行进行计数,以到达创建新列的下一个1
。所以输出将是一个像这样的列:
'one_hot' 'new_col'
1 0 1
2 1 0
3 0 3
4 0 2
5 0 1
6 1 0
到目前为止,写的注释对最后一个“ one_hot”值是1
很有用,但是如果它是0
怎么办?有什么可以做的吗?理想情况下,我会计算自上一个1
起的数据帧的长度,并用它来填充和
答案 0 :(得分:1)
使用:
#mask for filter out last 0 group
mask = df['one_hot'].iloc[::-1].cumsum().ne(0)[::-1]
#compare by value to mask
a = df['one_hot'] == 0
#create groups with inverse Series
b = a[::-1].cumsum()
#count only rows by mask, assign to new column
c = (b-b.where(~a).ffill().fillna(0).astype(int)).where(mask, 0)
df['new'] = c
print (df)
one_hot new
1 0 1
2 1 0
3 0 3
4 0 2
5 0 1
6 1 0
答案 1 :(得分:1)
一种方法是从颠倒顺序开始,检查哪里有1
并取cumsum
并将结果用作分组器,最后取每个的GroupBy.cumcount
组:
s = df.loc[::-1,'one_hot']
g = s.eq(1).cumsum()
df['new_col'] = s.groupby(g).cumcount().iloc[::-1]
print(df)
one_hot new_col
1 0 1
2 1 0
3 0 3
4 0 2
5 0 1
6 1 0