Skip to content
Advertisement

Sort a dict of DataFrames

I have a dict of data-frames like the following:

symbols ={BTC: DF, ETH: DF, DOGE:df}

where each DF looks like this.

index   price   price_change
0        10.    0
1        15     50
2        30     100
3        10     -50

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.

symbols = {
    'BTC':pd.DataFrame({
        'index': {0: 0, 1: 1, 2: 2, 3: 3},
        'price': {0: 10.0, 1: 15.0, 2: 30.0, 3: 10.0},
        'price_change': {0: 0, 1: 50, 2: 100, 3: -50}}),
    'ETH':pd.DataFrame({
        'index': {0: 0, 1: 1, 2: 2, 3: 3},
        'price': {0: 10.0, 1: 15.0, 2: 30.0, 3: 10.0},
        'price_change': {0: 0, 1: 50, 2: 100, 3: -10}})
}

{k:symbols[k] for k in sorted(symbols, key=lambda x: symbols[x].price_change.iloc[-1], reverse=True)}

Output

{'ETH':    index  price  price_change
 0      0   10.0             0
 1      1   15.0            50
 2      2   30.0           100
 3      3   10.0           -10,
 'BTC':    index  price  price_change
 0      0   10.0             0
 1      1   15.0            50
 2      2   30.0           100
 3      3   10.0           -50}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement