Reputation: 1137
I have a pandas dataframe that looks like the one below:
A | B | C | D | E |
1 | 2 | 3.5 | 2.3 | 4.0 |
I want to always extract any columns C through E that are greater than 2.5 and sort them in descending order of their values.
For the above example:
E,C is the output
Upvotes: 1
Views: 469
Reputation: 164773
One way is to extract values for your required columns via pd.DataFrame.columns.get_loc
. Then filter and use the pd.Series.index
:
vals = df.iloc[0, df.columns.get_loc('C'):] # or df.loc[0, 'C':]
res = vals[vals > 2.5].sort_values(ascending=False).index
print(res)
Index(['E', 'C'], dtype='object')
Upvotes: 1
Reputation: 402814
transpose
+ sort_values
v = df.T.squeeze().loc['C':'E'].sort_values(ascending=False)
v.index[v.gt(2.5)].tolist()
['E', 'C']
stack
+ sort_values
v = (
df.stack()
.reset_index(level=0, drop=True)
.loc['C':'E']
.sort_values(ascending=False)
)
v.index[v.gt(2.5)].tolist()
['E', 'C']
Upvotes: 2