Skip to content

Instantly share code, notes, and snippets.

@Marlysson
Last active September 16, 2021 00:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Marlysson/27e21fb7b8ac89888abf66230f1a370c to your computer and use it in GitHub Desktop.
Save Marlysson/27e21fb7b8ac89888abf66230f1a370c to your computer and use it in GitHub Desktop.
Challenge of pre process a csv file comma separated values with money cents with comma too
ITEM1 1 11 COMPRA1 444444 00 3312 22
ITEM1 1 11 COMPRA3 444444 00 3312 22
ITEM1 1 13 COMPRA2 444444 00 3312 22
ITEM1 1 90 COMPRA3 444444 00 3312 22
ITEM2 1 20 COMPRA2 444444 00 3312 22
ITEM2 2 19 COMPRA1 444444 00 3312 22
ITEM2 1 11 COMPRA1 444444 00 3312 22
ITEM2 1 12 COMPRA2 444444 00 3312 22
ITEM3 1 11 COMPRA1 444444 00 3312 22
ITEM3 5 60 COMPRA3 444444 00 3312 22
ITEM4 220 00 COMPRA2 444444 00 3312 22
import pandas as pd
# Separando colunas para tratamento
colunas_para_manter = [0,3]
colunas_para_processar = [1,2,4,5,6,7]
# Lendo dataframes e separando para tratamento
dataframe_original = pd.read_csv("teste.csv", usecols=colunas_para_manter)
dataframe_original.columns=['coluna_1', 'coluna_2']
# Criando colunas para o dataframe a ser processado para melhor tratá-lo por índices
dataframe_para_processar = pd.read_csv("teste.csv", usecols=colunas_para_processar)
colunas = ["numero_" + str(int(numero)+1) for numero in range(len(dataframe_para_processar.columns))]
dataframe_para_processar.columns = colunas
# Criando novo dataframe e utilizando pares de colunas para formar o número
df_com_numeros = pd.DataFrame()
df_com_numeros["numero_1"] = dataframe_para_processar["numero_1"].map(str) + "." + dataframe_para_processar['numero_2'].map(str)
df_com_numeros['numero_2'] = dataframe_para_processar['numero_3'].map(str) + "." + dataframe_para_processar['numero_4'].map(str)
df_com_numeros['numero_3'] = dataframe_para_processar['numero_5'].map(str) + "." + dataframe_para_processar['numero_6'].map(str)
# Este passo já está explícito
df_com_numeros['numero_1'] = pd.to_numeric(df_com_numeros['numero_1']).map(float)
df_com_numeros['numero_2'] = pd.to_numeric(df_com_numeros['numero_2'].map(float))
df_com_numeros['numero_3'] = pd.to_numeric(df_com_numeros['numero_3'].map(float))
# Criando um novo dataframe com as colunas originais e com os novos números formados
novo_df = pd.concat([dataframe_original, df_com_numeros], axis=1)
print(novo_df)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment