选择数据帧 [英] Selecting the dataframe

查看:0
本文介绍了选择数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据帧如下:

   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月。因此,预期输出为DataFrame:

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

如何转换?谢谢

推荐答案

您可以先将Tahun设置为index来使用您的解决方案:

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的解决方案,但为了正确排序,请将Month转换为已排序的类别:
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

这篇关于选择数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆