我有一个带有排序索引F
的pandas数据框I
。我有兴趣了解其中一个专栏的最后一个更改,让我们说A
。特别是,我想构建一个与F
具有相同索引的系列,即I
,其i
的值为j
,其中j
最大索引值小于i
,使F[A][j] != F[A][i]
。例如,请考虑以下框架:
A
1 5
2 5
3 6
4 2
5 2
所需的系列将是:
1 NaN
2 NaN
3 2
4 3
5 3
有没有一个熊猫/ numpy习惯的方式来构建这个系列?
答案 0 :(得分:0)
试试这个:
df['B'] = np.nan
last = np.nan
for index, row in df.iterrows():
if index == 0:
continue
if df['A'].iloc[index] != df['A'].iloc[index - 1]:
last = index
df['B'].iloc[index] = last
这将创建一个包含结果的新列。我相信在您通过它们时更改行不是一个好主意,之后您可以简单地替换列并删除另一个,如果您愿意。
答案 1 :(得分:0)
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