How to make a "procv" in Python using the Pandas library

Good afternoon!

I have the csv below:

Nome      Vendas      Produto       Data
Carlos     83,40       cod2       15/04/2020
Andre      70,50       cod5       10/04/2020
Cristina    100        cod7       25/04/2020
Carlos     20,80       cod1       03/04/2020
Gisele     10,50       cod9       11/04/2020
Andre      33,70       cod6       30/04/2020

I put only one piece for example and demonstrate my idea.

I need it to look like this: Let the columns have the names and below each name the value of the sales.

Carlos  Andre  Cristina  Gisele
83,40   70,50   100       10,50
20,80   33,70

Well, the first step was to try to assemble this structure. I used the code below:

import pandas as pd
import codecs

arquivo = pd.read_csv(codecs.open("C:\\Users\\Desktop\\Python\\relatorio.csv", "rU", "ansi"),sep=';',infer_datetime_format=True, index_col=False)
arquivo.columns = ['Nome','Vendas']

Nomes = arquivo[['Nome']]
Nomes = Nomes.drop_duplicates(subset = ['Nome'])
Nomes = Nomes.reset_index()

Nomes_drop = Nomes.drop(columns = ['index'])
Nomes_Colunas = Nomes_drop.T.reset_index()

Now I have no idea how to do this "procv" to bring the sales information to the respective ones column. Could someone help me?

Author: Felipe Ferreira, 2020-05-15

2 answers

We can make a unstack after a GroupBy :

df.groupby('Nome')['Vendas'].apply(lambda df: df.reset_index(drop=True)).unstack(0)
 1
Author: drec4s, 2020-05-15 22:41:59

You can group by name to join the vedas of each person and then iterate over the groups to grab the data. From this build a new dataframe.

Sales.txt file

Nome,Vendas,Produto,Data
Carlos,83.40,cod2,15/04/2020
Andre,70.50,cod5,10/04/2020
Cristina,100,cod7,25/04/2020
Carlos,20.80,cod1,03/04/2020
Gisele,10.50,cod9,11/04/2020
Andre,33.70,cod6,30/04/2020
import pandas as pd

df = pd.read_csv("vendas.csv")
# Vamos manter apenas as colunas "Nome" e "Vendas"
df = df[["Nome", "Vendas"]]

# Vamos agrupar por nome
grouped = df.groupby("Nome")

# Número de vendas -> Vai ser o número de linhas do dataframe final
num_vendas = grouped.count().max()[0]


def to_list_fixed_size(series, size):
    """
    Converte `series` para uma lista e se o tamanho dessa lista for menor que
    `size`, adiciona tantos elementos `None` quanto necessário.
    """
    l = list(series)
    if len(l) < size:
        l.extend([None] * (size - len(l)))
    return l

# Cada chave no dicionário corresponde ao nome de um vendedor e o valor
# associado é uma lista com as vendas. A função "to_list_fixed_size" definida
# antes garante que as listas com as vendas de todos os vendedores possua o
# mesmo tamanho para que possamos criar um dataframe depois com esse dicionário.
data = {i: to_list_fixed_size(j.Vendas, num_vendas) for i,j in grouped}

df2 = pd.DataFrame(data)

The Final DataFrame looks like below

   Andre  Carlos  Cristina  Gisele
0   70.5    83.4     100.0    10.5
1   33.7    20.8       NaN     NaN
 0
Author: darcamo, 2020-05-15 20:26:37