Combining Tuples and Lists into Dataframe

Viewed 16

I have the following code that is giving me a constant + a list of tuples in my return values:

for name in ours_list:
    print(name, process.extract(name, snow_list, limit=5))

Returns:

Remote Access Migration [('Remote Access Migration', 100), ('Migrate Application Access', 86), ('Migration of Z75', 86), ('Network Access', 86), ('Remote Control Access Hardening', 86)]

But I'm looking for a DataFrame:

Name  |  Pick 1 | Pick 2 ....
Remote Access Migration  |  Remote Access Migration (100) | Migrate Application Access (86) ....

Any ideas on how to adjust my code? I'd imagine it's a join the list together and then create a list of lists and combine that into a large dataframe?

1 Answers

depending on the structure of you data, use list compression and call a list[tuple[key,value]] -> to a dict to cleanly build a pandas dataframe

import pandas as pd
def process_extract(name: str, limit: int):
    data = {
        "Remote Access Migration": [
            ("Remote Access Migration", 100),
            ("Migrate Application Access", 86),
            ("Migration of Z75", 86),
            ("Network Access", 86),
            ("Remote Control Access Hardening", 86),
        ],
        "Some Other Junk": [
            ("Blah1", 10),
            ("Blah2", 10),
            ("Blah3", 10),
            ("Blah4", 10),
            ("Blah5", 10),
            ("Blah6", 10),
            ("Blah7", 10),
            ("Blah8", 10),
        ],
    }
    return data[name][:limit]


ours_list = ["Remote Access Migration", "Some Other Junk"]


pd.DataFrame([dict(process_extract(name, limit=5)) for name in ours_list], index=ours_list).T


                                 Remote Access Migration  Some Other Junk
Remote Access Migration                            100.0              NaN
Migrate Application Access                          86.0              NaN
Migration of Z75                                    86.0              NaN
Network Access                                      86.0              NaN
Remote Control Access Hardening                     86.0              NaN
Blah1                                                NaN             10.0
Blah2                                                NaN             10.0
Blah3                                                NaN             10.0
Blah4                                                NaN             10.0
Blah5                                                NaN             10.0
Related