getting dataframe based on condition in dictionary in python

Question:

I have a enigmatic task in Python. From API I receive a dictionary as shown below. From this response (dictionary) I have to make df which two columns. First is the SapId and the second is OOSOperation but only with rows where OOSOperation = ‘OutOfStock’. Could anyone please help me with this task? I include picture.

Dictionary case

Asked By: Firts_is_science

||

Answers:

You could either prefilter with

list_of_elements.filter(lambda element: element["OOSOperation"] == 'OutOfStock')

or just filter the DF afterwards with

df[df["OOSOperation"] == 'OutOfStock']
Answered By: Lukas Schmid

I am not sure if I understand correctly, but maybe this is close to what you want:

products = data['Products'][:]

out_of_stock_products =[]

for product_dict in products:
  if product_dict['OOSOperation'] == 'OutOfStock':
    out_of_stock_products.append(product_dict)

df = pd.DataFrame(out_of_stock_products)

Alternatively, using list comprehension:

products = data['Products'][:]

out_of_stock_products = [d for d in products if d['OOSOperation'] =='OutOfStock']

df = pd.DataFrame(out_of_stock_products)
Answered By: Isaac Rene
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.