AAA*_*AAA 6 python dataframe pandas
我有一个数据框如下。
test = pd.DataFrame({'col1':[0,0,1,0,0,0,1,2,0], 'col2': [0,0,1,2,3,0,0,0,0]})
col1 col2
0 0 0
1 0 0
2 1 1
3 0 2
4 0 3
5 0 0
6 1 0
7 2 0
8 0 0
Run Code Online (Sandbox Code Playgroud)
对于每一列,我想在每一列的最大值之前找到值1的索引。例如,对于第一列,最大值是2,在2之前的值1的索引是6。对于第二列,最大值是3,在3之前的值1的索引是2。
总之,我希望获得[6,2]作为此测试DataFrame的输出。有没有一种快速的方法来实现这一目标?
使用Series.mask那些不是1隐藏的元素,然后应用Series.last_valid_index到每一列。
m = test.eq(test.max()).cumsum().gt(0) | test.ne(1)
test.mask(m).apply(pd.Series.last_valid_index)
col1 6
col2 2
dtype: int64
Run Code Online (Sandbox Code Playgroud)
使用numpy进行向量化,可以使用numpy.cumsum和argmax:
idx = ((test.eq(1) & test.eq(test.max()).cumsum().eq(0))
.values
.cumsum(axis=0)
.argmax(axis=0))
idx
# array([6, 2])
pd.Series(idx, index=[*test])
col1 6
col2 2
dtype: int64
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |