Skip to content Skip to sidebar Skip to footer

Selecting The Dataframe

I have dataframe like this: 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

Solution 1:

You can use your solution with set Tahun to index first:

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
02021   Jul   0.08

Or solution with melt, but for correct ordering is convert Months to ordered Categorical:

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

Post a Comment for "Selecting The Dataframe"