Check that the data of a CSV file changes and print the error - Python

2

I have to make a file in Python that controls a file ". csv" , and if any parameter changes, indicate what value has changed, and if it matches the expected output.

ELEMENTO1,1,1,0,-1,0,-1

When you change a column, it would be:

ELEMENTO1,1,1,0,-1,1,0

I would have to pass it through a code that looks up the changed value and compare it to see if the value is 0,1-1 and give a different message ( 0:Ok, 1:Pendiente, -1:ERROR ).

    
asked by AlberM 13.11.2016 в 12:58
source

1 answer

1

this is easier to do with the dataframes of the panda library, I'll give you an example of what I would do:

#Importamos las librerias correspondientes,
import pandas as pd
import numpy as np

# Esto lo he tenido que hacer para que lea desde una variable que sea un string, sino usar pd.from_csv(path_del_fichero)
import sys
if sys.version_info[0] < 3: 
    from StringIO import StringIO
else:
    from io import StringIO
# He añadido la primera fila como nombre de columnas, para luego saber la diferencia en que columna esta
TESTDATA=StringIO(
    """header,1,2,3,4,5,6
    ELEMENTO1,1,1,0,-1,0,-1""")
TESTDATA2=StringIO(
    """header,1,2,3,4,5,6
    ELEMENTO1,1,1,0,-1,0,1""")

# Construimos los dos dataframes
df1 = pd.read_csv(TESTDATA, header=0)
df2 = pd.read_csv(TESTDATA2, header=0)

# Comparamos la diferencia
difference_locations = np.where(df1 != df2)
changed_from = df1.values[difference_locations]

changed_to = df2.values[difference_locations]
df = pd.DataFrame({'from': changed_from, 'to': changed_to}, index=changed.index)

# Devolvemos un diccionario con las diferencias:
df.to_dict()

# Esto devolvería algo asi, que viene a decir que en la columna '6' pasa de(from) -1 a(to) 1.
{'from': {(0, '6'): -1}, 'to': {(0, '6'): 1}}
    
answered by 13.08.2017 в 13:02