Home > Mobile >  Sort a list of dataframes
Sort a list of dataframes

Time:01-20

I have a huge list of data frames that I want to sort by name

Example:

Data_frames_list = [sensor 1 (South), sensor 6 (North), sensor 3 (South), sensor 1 (North), ...]

I would like to sort it by the sensor number (those are data frames names containing tons of rows).

Final result example:

Data_frames_list = [sensor 1 (South), sensor 1 (North), sensor 2 (South), sensor 2 (North), sensor 3 (South), ...]

Does anybody have an idea how I could proceed?

CodePudding user response:

you'll need to get the variable name before sorting. You can get the variable name by creating a function like:

def namestr(obj, namespace, prefix='sensor'):
    for name in namespace:
        if namespace[name] is obj and name.startswith(prefix):
            return name

then you can use this method to sort the list like:

Data_frames_list.sort(key=lambda df: namestr(df, globals()))

in namestr() function, prefix argument is used because there could be issues in sorting if there's another variable pointing to dataframe as globals() will return dictionary of all current global symbol table

NOTE: The code will sort based on the variable name which is a string, so sensor 11 will come before sensor 2.

  •  Tags:  
  • Related