I have a dict of data-frames like the following:
symbols ={BTC: DF, ETH: DF, DOGE:df}
where each DF looks like this.
JavaScript
x
6
1
index price price_change
2
0 10. 0
3
1 15 50
4
2 30 100
5
3 10 -50
6
I am trying to sort the dict by the price_change in the last row.
Advertisement
Answer
You could figure out the sorting of the keys by using a lambda function on sorted, which gets the last price change per df. Using reverse=True
would sort them in the order I believe you are looking for. Then it’s a matter of reconstructing a new dict in that order using dict comprehension.
JavaScript
1
13
13
1
symbols = {
2
'BTC':pd.DataFrame({
3
'index': {0: 0, 1: 1, 2: 2, 3: 3},
4
'price': {0: 10.0, 1: 15.0, 2: 30.0, 3: 10.0},
5
'price_change': {0: 0, 1: 50, 2: 100, 3: -50}}),
6
'ETH':pd.DataFrame({
7
'index': {0: 0, 1: 1, 2: 2, 3: 3},
8
'price': {0: 10.0, 1: 15.0, 2: 30.0, 3: 10.0},
9
'price_change': {0: 0, 1: 50, 2: 100, 3: -10}})
10
}
11
12
{k:symbols[k] for k in sorted(symbols, key=lambda x: symbols[x].price_change.iloc[-1], reverse=True)}
13
Output
JavaScript
1
11
11
1
{'ETH': index price price_change
2
0 0 10.0 0
3
1 1 15.0 50
4
2 2 30.0 100
5
3 3 10.0 -10,
6
'BTC': index price price_change
7
0 0 10.0 0
8
1 1 15.0 50
9
2 2 30.0 100
10
3 3 10.0 -50}
11