Python - take csv values under certain conditions

Asked

Viewed 76 times

0

I am new in python and am trying to get information from a CSV and pass to JSON.

The CSV is of this format:

QTD    Produto          Estoque_Limitado    
20      pipoca               1      
19      refrigerante         1       
21      doces                0      

"Stock_limited" would be a boolean, so if you have in stock would be 1, if you are 0 would need to replace

The question is as follows, as taken from csv in this dynamical way?

json is like this:

{
"indisponivel":{
"produto": "doces",
"quantidade": 21,
"Estoque": "Reposição necessária"
    }
}

I’m taking by python the name of the product and the quantity already, but I need this condition to pick over the stock

Pyhton:

import pandas as pd
import json

data = pd.read_csv(r"monitoramento.csv", sep=";")

#Trazendo dados fixos

produto=data['Produto']
quantidade = data['QTD']

all products that were 0, would need to enter the json and there would be more products than those 3 that I mentioned.

Anyone who can help, thank you

1 answer

0


With a dictionary understanding it becomes simple to do, using the function zip to iterate over the columns side by side and always checking if the column 'Estoque_Limitado' has a zero value:

import pandas as pd

data = pd.read_csv(r"monitoramento.csv", sep=";")

produto = data['Produto']
quantidade = data['QTD']
estoque = data['Estoque_Limitado']

resultado = {
    'indisponivel': [{
        'produto': pd, 
        'quantidade': qt, 
        'Estoque': 'Reposição necessária'
        } 
    for pd, qt, es in zip(produto, quantidade, estoque) if es == 0
    ]
}

print(resultado)

Output (note that the object associated with the key 'indisponivel' is an array of objects, since there may be multiple objects unavailable):

{
    'indisponivel': [{
        'produto': 'doces',
        'quantidade': 21,
        'Estoque': 'Reposição necessária'
    }]
}

I tried to keep the same logic as your code, but note that it can be costly to iterate over all lines of your CSV during dictionary comprehension.

If this is a problem, select the original table (e.g. using loc) before making the dictionary understanding (there also we do not need to use the conditional within the understanding, because the values have already been selected):

import pandas as pd

data = pd.read_csv(r"monitoramento.csv", sep=";")

filtered = data.loc[data['Estoque_Limitado'] == 0]
produto = filtered['Produto']
quantidade = filtered['QTD']

resultado = {
    'indisponivel': [{
        'produto': pd, 
        'quantidade': qt, 
        'Estoque': 'Reposição necessária'
        } 
    for pd, qt in zip(produto, quantidade)
    ]
}

print(resultado)

The output generated is the same as before.

  • I managed to pull the data this way, thank you very much! helped a lot

Browser other questions tagged

You are not signed in. Login or sign up in order to post.