繁体   English   中英

返回最后一个非零值

[英]return the last non-zero value

我有一个类似于这个的 DataFrame。

name company count_2017 count_2018 count_2019 last_id
joe     abc     1           0         2         230283
cindy   bcd     0           2         0         239382
john    cde     0           1         0          238372
wang    def     0           0         3          1332

我需要返回最后一个非零值及其年份

name company count_2017 count_2018 count_2019 last_id.   year
joe     abc     1           0         2         230283   2019
cindy   bcd     0           2         0         239382   2018
john    cde     0           1         0          238372. 2018
wang    def     5           0         0          1332    2017

生成的“年”列是最后一个非零列的名称。 例如,在“joe”行中,最后一个非零值是 2,那么我返回 2019 年。

我用代码

columns_first = df[[f'count_{yr}' for yr in range(2000, YEAR)]]
col_first = columns_first.columns
df["FIRST_YEAR"] = (columns_first.select_dtypes(float)
                 .gt(0)
                 .dot(col_first.str[-4:] + " ")
                 .str.split()
                 .str[0])

但是,我不能返回最后一个非零值,我只能得到第一个非零值。 有没有办法修复这段代码?

返回应该是原来的栏目加上上面的年份栏目 year 2019 2018 2018 2017

你可以做idxmax

df.filter(like='count_').ne(0).iloc[:,::-1].idxmax(1).str.split('_').str[-1]
0    2019
1    2018
2    2018
3    2019
dtype: object

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM