数据帧 - 基于其他列的值的时间戳之间的时间跨度。

问题描述 投票:1回答:1

我有一个pandas数据框架,其中的指数包含年数,而一列包含股息支付。现在我想确定该公司已经连续支付了多少年的股息(列股息> 0)。

作为一个例子,对于下面的表格,我希望结果是2(2019+2018)

year dividend
2019 1.89
2018 1.70
2017 0
2016 1.5

而对于这个4

year dividend
2019 1.89
2018 1.70
2017 1.6
2016 1.58
pandas
1个回答
0
投票

虽然下面的答案是一个绕口令,但它可以解决你的问题。

将其转换为 pd.df 并使用 idxmin()n() 包装器来寻找连续的除法报酬。

year dividend
2019 1.89
2018 1.70
2017 0
2016 1.5

df = pd.DataFrame({'dividend' : [1.89,1.70,0,1.5]}, index=[2019,2018,2017,2016])
print('Continuous Divident value :', df.loc[ : df.dividend.idxmin()].ne(0).sum()[0])

Continuous Divident value : 2

year dividend
2019 1.89
2018 1.70
2017 1.6
2016 1.58

df = pd.DataFrame({'dividend' : [1.89,1.70,1.6,1.58]}, index=[2019,2018,2017,2016])
print('Continuous Divident value :', df.loc[ : df.dividend.idxmin()].ne(0).sum()[0])

Continuous Divident value : 4

编辑

根据你的意见,我刚刚玩了一下循环,希望能满足你的要求。如果不能满足,请告诉我。

value = 0 if df['bool'].iloc[0] == 0 else (len(df) if len(df) == df.iloc[-1::]['bool'].values[0] else len(df.loc[: df[df['bool'].duplicated(keep = 'last')].index[0]]))
print('Continous divident value : ', value)
© www.soinside.com 2019 - 2024. All rights reserved.