【问题标题】:Pandas: Index of last non equal rowPandas:最后一个不相等行的索引
【发布时间】:2016-01-21 04:21:28
【问题描述】:

我有一个带有排序索引I 的熊猫数据框F。我有兴趣了解其中一列的最后一次更改,比如说A。特别是,我想构造一个与F具有相同索引的系列,即I,其在i处的值为j,其中j是小于i的最大索引值使得@ 987654330@。例如,考虑以下框架:

  A
1 5
2 5
3 6
4 2
5 2

想要的系列是:

1 NaN
2 NaN
3   2
4   3
5   3

有没有一种 pandas/numpy 惯用的方式来构建这个系列?

【问题讨论】:

  • 这真是令人困惑。例如,什么是“当前行”?
  • 啊???描述仍然很混乱。

标签: python pandas indexing dataframe


【解决方案1】:

试试这个:

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

这将创建一个包含结果的新列。我认为在通过它们时更改行不是一个好主意,之后您可以简单地替换一列并根据需要删除另一列。

【讨论】:

  • 我希望有一种方法可以避免在 python 中循环。通常 pandas 或 numpy 函数要快得多
  • 我认为它的效率并没有显着提高。此外,当您想在持有索引的同时循环遍历它,您可能需要使用旧的“for”。不过,我可能错了。
【解决方案2】:

np.argmaxpd.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

【讨论】:

    猜你喜欢
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 2016-07-14
    • 2023-04-09
    • 2022-01-09
    • 2020-05-16
    相关资源
    最近更新 更多