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.
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']
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)
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.
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']
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)