Filtering columns based on last row value

Viewed 645

I have a dataframe and added the last row with totals.

import pandas as pd
df = pd.DataFrame({'D': {0: 6, 1: 4, 2: 6},
                    'A': {0: 1, 1: 2, 2: 3},
                    'C': {0: 2, 1: 7, 2: 5},
                    'B': {0: 4, 1: 5, 2: 6}})
df = df.append(df.sum(), ignore_index=True)
df

    D  A   C   B
0   6  1   2   4
1   4  2   7   5
2   6  3   5   6
3  16  6  14  15

How can I filter, e.g. leave only columns which the last row value (total) is above 10? Expected output:

    D  C   B
0   6  2   4
1   4  7   5
2   6  5   6
3  16 14  15
1 Answers

You can select the last row using DataFrame.iloc then use Series.gt to create boolean mask, then use this mask with DataFrame.loc to filter the required columns:

df.loc[:, df.iloc[-1].gt(10)]

    D   C   B
0   6   2   4
1   4   7   5
2   6   5   6
3  16  14  15
Related