[英]How to get the index of the first non-zero value for a pandas dataframe column
[英]How to get max column with non-zero value in a pandas dataframe
我有一個這樣的數據框:
2017 2018 2012 2015 2014 2016
11647 0.044795 0.000000 0.000000 0.0 0.0 0.0
16389 0.089801 0.044900 0.000000 0.0 0.0 0.0
16404 0.014323 0.000000 0.000000 0.0 0.04 0.0
16407 0.052479 0.010442 0.009277 0.0 0.0 0.0
16409 0.000000 0.000000 0.004883 0.0 0.0 5.0
請注意,列未排序。 對於每一行,我需要獲取非零值的最新年份。 因此,預期結果是:
11647 2017
16389 2018
16404 2017
16407 2018
16409 2016
怎么做?
可以在已排序的df中使用idxmax
df[sorted(df.columns, reverse=True)].ne(0).idxmax(1)
11647 2017
16389 2018
16404 2017
16407 2018
16409 2016
dtype: object
與max
使用stack
df[df.ne(0)].stack().reset_index(level=1)['level_1'].max(level=0)
Out[386]:
11647 2017
16389 2018
16404 2017
16407 2018
16409 2016
Name: level_1, dtype: int64
只是更新
df.ne(0).mul(df.columns).max(1)
Out[423]:
11647 2017.0
16389 2018.0
16404 2017.0
16407 2018.0
16409 2016.0
dtype: float64
df.apply(lambda row: row[row > 0].index.max(), axis=1)
給出預期的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.