这是我的DataFrame:
import pandas as pd
df = pd.DataFrame(
{
'a': [100, 1123, 123, 100, 1, 0, 1],
'b': [1000, 11123, 1123, 0, 55, 0, 1],
},
index=range(100, 107)
)
这是预期输出.我想创建列c
:
a b c
100 100 1000 NaN
101 1123 11123 NaN
102 123 1123 NaN
103 100 0 3.0
104 1 55 NaN
105 0 0 NaN
106 1 1 NaN
使用的掩码是:
mask = ((df.a > df.b))
我想得到出现mask
的第一行的索引.我想保留原始索引,但得到reset_index()
值.在该示例中,掩码的第一实例位于索引3
处.
我可以通过以下方法获得第一个掩码实例:
df.loc[mask.cumsum().eq(1) & mask, 'c'] = 'the first row'
但我不知道如何获取索引.