【问题标题】:How to apply masking while creating next row value which is based on previous row's value and another column in Python Pandas?如何在创建基于上一行值和 Python Pandas 中的另一列的下一行值时应用屏蔽?
【发布时间】:2020-05-29 04:05:40
【问题描述】:

这是数据

import numpy as np
import pandas as pd

data = {
    'cases': [120, 100, np.nan, np.nan, np.nan, np.nan, np.nan],
    'percent_change': [0.03, 0.01, 0.00, -0.001, 0.05, -0.1, 0.003],
    'tag': [7, 6, 5, 4, 3, 2, 1],
}

   cases  percent_change  tag
0  120.0           0.030    7
1  100.0           0.010    6
2    NaN           0.000    5
3    NaN          -0.001    4
4    NaN           0.050    3
5    NaN          -0.100    2
6    NaN           0.003    1

我想将下一个案例的值创建为(下一个值)=(上一个值)*(1+当前 per_change)。具体来说,我希望它在标记值小于 6 的行中完成(并且我必须使用掩码(即,df.loc 用于此行选择)。这应该给我:

   cases  percent_change  tag
0  120.0           0.030    7
1  100.0           0.010    6
2  100.0           0.000    5
3   99.9          -0.001    4
4  104.9           0.050    3
5   94.4          -0.100    2
6   94.7           0.003    1

我试过了,但它不起作用:

df_index = np.where(df['tag'] == 6)
index = df_index[0][0]
df.loc[(df.tag<6), 'cases'] = (df.percent_change.shift(0).fillna(1) + 1).cumprod() * df.at[index, 'cases']

        cases  percent_change  tag
0  120.000000           0.030    7
1  100.000000           0.010    6
2  104.030000           0.000    5
3  103.925970          -0.001    4
4  109.122268           0.050    3
5   98.210042          -0.100    2
6   98.504672           0.003    1

【问题讨论】:

    标签: python-3.x pandas data-science


    【解决方案1】:

    我愿意:

    s = df.cases.isna()
    percents = df.percent_change.where(s,0)+1
    df['cases'] = df.cases.ffill()*percents.cumprod()
    

    输出:

            cases  percent_change  tag
    0  120.000000           0.030    7
    1  100.000000           0.010    6
    2  100.000000           0.000    5
    3   99.900000          -0.001    4
    4  104.895000           0.050    3
    5   94.405500          -0.100    2
    6   94.688716           0.003    1
    

    更新:如果你真的坚持要屏蔽Tag==6:

    s = df.tag.eq(6).shift()
    s = s.where(s).ffill()
    
    percents = df.percent_change.where(s,0)+1
    df['cases'] = df.cases.ffill()*percents.cumprod()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-04
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多