Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get values from a dataframe based on a nested list in Python

I have a dataframe in Python called "Item_Table" and it looks like the below:

--------------------------
item_id | item_description
--------------------------
N4      | Steel
M3      | Oil
B1      | Water
X9      | Coal
Z5      | Plastic
--------------------------

I also have a nested orders list which looks like below. Each list inside the nested list represents one order. One order can have multiple items

orders = [[Z5], [X9, Z5], [B1, Z5, N4], [B1, X9]]

Ideally, I would like to return a nested list with the respective item_descriptions from the "Item_Table" which looks like the below nested list:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

orders_descriptions = [[Plastic], [Coal, Plastic], [Water, Plastic, Steel], [Water, Coal]]

I tried a solution where I converted orders list to a dataframe and tried to merge that with item_table to get item_descriptions but because one order has multiple items, I am unable to do the join.

>Solution :

You can try export the item_id and item_description to dictionary then loop the orders

d = df.set_index('item_id')['item_description'].to_dict()

orders_descriptions = [[d[o] for o in os] for os in orders]
print(orders_descriptions)

[['Plastic'], ['Coal', 'Plastic'], ['Water', 'Plastic', 'Steel'], ['Water', 'Coal']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading