np.argmax
或pd.Series.argmax
關於布爾數據可以幫助您找到第一個(或在這種情況下,最後一個)True
值。不過,你仍然需要在這個解決方案中循環播放。
# Initiate source data
F = pd.DataFrame({'A':[5,5,6,2,2]}, index=list('fobni'))
# Initiate resulting Series to NaN
result = pd.Series(np.nan, index=F.index)
for i in range(1, len(F)):
value_at_i = F['A'].iloc[i]
values_before_i = F['A'].iloc[:i]
# Get differences as a Boolean Series
# (keeping the original index)
diffs = (values_before_i != value_at_i)
if diffs.sum() == 0:
continue
# Reverse the Series of differences,
# then find the index of the first True value
j = diffs[::-1].argmax()
result.iloc[i] = j
這真是令人困惑。例如,「當前行」是什麼? – ako
爲清晰起見進行了編輯。 –
huh ???描述仍然非常混亂。 – Alexander