我有一个大数据框,如果行没有通过过滤器,我想添加一个为 -1 的列,或者如果它通过过滤器,则添加一个索引。例如,在数据框中
b f j passed new_index
1 12 5 6 Y 0
2 4 99 2 Y 1
3 10 77 16 N -1
4 4 99 2 Y 2
5 10 77 16 N -1
6 4 99 2 Y 3
7 10 77 16 N -1
该列new_index
是我添加的,基于 column passed
。如果没有 iterrows,我该如何做到这一点?我创建了一个系列bool4
,在True
那里passed == Y
和False
其他地方,并尝试:
df.loc[bool4, 'new_index'] = df.loc[bool4, 'new_index'].apply([lambda i: i for i in range(sum(bool4))])
但它不会更新new_index
列(将其留空)。
让我们使用eq
, cumsum
, add
, 和mask
:
df['new_index'] = df.passed.eq('Y').cumsum().add(-1).mask(df.passed == 'N', -1)
输出:
b f j passed new_index
1 12 5 6 Y 0
2 4 99 2 Y 1
3 10 77 16 N -1
4 4 99 2 Y 2
5 10 77 16 N -1
6 4 99 2 Y 3
7 10 77 16 N -1
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句