首页 > 解决方案 > 选择数据框

问题描述

我有这样的数据框:

   Tahun  Jan   Feb     Mar     Apr     Mei     Jun     Jul     Ags     Sep     Okt     Nov     Des
0  2020   0.39  0.28    0.10    0.08    0.07    0.18    -0.10   -0.05   -0.05   0.07    0.28    0.45
1  2021   0.26  0.10    0.08    0.13    0.32    -0.16   0.08    0.00    0.00    0.00    0.00    0.00

我想选择 != 0.00 的当前值,该值是 2021 年 7 月的值。因此,预期的输出是数据框:

Tahun  Month  Value
2021   Jul    0.08  

我做了:

dfs = df.where(df != 0.00).stack()
r, c = dfs.last_valid_index()
x = dfs.loc[r, [c, 'Tahun']]

输出如下:

1  Tahun    2021.00
   Jul         0.08
dtype: float64

如何转换?谢谢

标签: pythonpandasdataframejoinmulti-index

解决方案


您可以将您的解决方案与 set Tahunto indexfirst 一起使用:

df = df.set_index('Tahun').rename_axis('Month', axis=1)

s = df.where(df != 0.00).stack()

df2 = s.loc[[s.last_valid_index()]].reset_index(name='Value')
print (df2)
   Tahun Month  Value
0   2021   Jul   0.08

或使用 的解决方案melt,但为了正确排序,将Months 转换为有序分类:

df = df.melt(id_vars=["Tahun"], 
        var_name="Month", 
        value_name="Value")

cats = ['Jan', 'Feb', 'Mar', 'Apr','Mei', 'Jun', 'Jul', 'Ags', 'Sep', 'Okt', 'Nov', 'Des']
df['Month'] = pd.Categorical(df['Month'], ordered=True, categories=cats)
df = df.sort_values(['Tahun','Month'])

df2 = df[df['Value'].ne(0)].tail(1)
print (df2)
    Tahun Month  Value
13   2021   Jul   0.08

推荐阅读