【问题标题】:Pull value n before last value in df将值 n 拉到 df 中的最后一个值之前
【发布时间】:2021-04-29 16:28:55
【问题描述】:

我有一个包含多个列的年度数据的 df。我有代码可以提取每列中的最后一个值,不包括 0。我想将第 n 行拉到我拉的行之前,问题是所有这些值的索引都不相同。我想在每个 col 上使用 df_periods 中的 n 来拉取之前的第 n 个值。我曾想过尝试索引我从 endval 获得的值,但因为它们不是来自同一行,所以它似乎不起作用。对此有什么想法吗?

df=
col1 col2 col3 col4 col5
8    9    6    7    1
8    9    6    7    1
8    9    6    7    1
8    9    6    7    1
8    9    6    7    NaN  
8    NaN  6    7    NaN  
8    NaN  6    7    NaN  
8    NaN  6    7    NaN  

df_periods=
col1 col2 col3 col4 col5
 4    3    5    4    4

endval = df.stack().groupby(level=1).last()

【问题讨论】:

    标签: python pandas numpy loops


    【解决方案1】:

    试试:

    # remove the `nan` values
    s = df.stack().reset_index(name='value')
    
    # enumerate date from bottom up
    count_from_bottom = s[::-1].groupby('level_1').cumcount()[::-1]
    
    # compare the enumeration with the respective threshold and extract data
    endval = s.loc[count_from_bottom < s['level_1'].map(df_periods.iloc[0])]
    

    输出:

        level_0 level_1  value
    4         0    col5    1.0
    9         1    col5    1.0
    11        2    col2    9.0
    14        2    col5    1.0
    16        3    col2    9.0
    17        3    col3    6.0
    19        3    col5    1.0
    20        4    col1    8.0
    21        4    col2    9.0
    22        4    col3    6.0
    23        4    col4    7.0
    24        5    col1    8.0
    25        5    col3    6.0
    26        5    col4    7.0
    27        6    col1    8.0
    28        6    col3    6.0
    29        6    col4    7.0
    30        7    col1    8.0
    31        7    col3    6.0
    32        7    col4    7.0
    

    【讨论】:

    • 谢谢!这可以从每个列中提取一组 (5) 行,但是如何在列之间改变 tail(n) 中的 n? (我想在 df 中的每个列上使用 df_periods 中的 n)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2023-02-21
    • 2021-03-04
    • 2023-01-09
    • 2023-02-01
    • 2019-08-29
    相关资源
    最近更新 更多