Replace values in a CSV Python

1

I'm lost with something. I have a csv file that I import with Pandas to be able to convert it into an Numpy array, and I have the following function to replace values in the original CSV file:

    # Cargamos el archivo en la variable data, como strings
    data_p = pd.read_csv(filename)
    data = np.array(data_p.values)
    # funcion saveData
    # Retorna el arreglo con el nuevo valor en los indices recibidos.
    # Guarda la información en el archivo
    def saveData(indicex,indicey,nuevo_valor):
        data[indicex][indicey] = nuevo_valor
        data_p.to_csv(filename,sep=',',mode='a')
        # np.savetxt(filename,data, delimiter=",",fmt="%s",header="Team,Group,Squad Number,Position,Player,Age,Club,Goals")
        return data

But when I want to use the function it does not overwrite the data, but it duplicates all the CSV data from the last row downwards, and this it does according to the number of times the for is repeated.

for g in range(2):
    if goles_partido[g] != 0:
        info_equipo = data23.obtenerInfoEquipo(partido[g + 1].title())
        for i in range(goles_partido[g]):
            indice_gol = random.randint(0, info_equipo.shape[0])
            nombre_jugador_gol = info_equipo[indice_gol - 1, 4]
            print(nombre_jugador_gol)
            posicion_jugador_data = np.where(data23.data == nombre_jugador_gol)
            print(posicion_jugador_data)
            gol_temp = int(data23.data[posicion_jugador_data[0], -1])
            print(gol_temp)
            gol_temp += 1
            gol_temp = str(gol_temp)
            print(gol_temp)
            data23.data = data23.saveData(posicion_jugador_data[0], -1, gol_temp)
            print(data23.data[posicion_jugador_data[0], -1])
goles_partido = []

The prints are only to check if the data is correctly overwritten at some time, which does not happen.

Could someone help me why this happens? And what should I do to get it properly overwritten?

Thank you!

    
asked by Brank Malatay 30.06.2018 в 18:45
source

1 answer

0

Your problem was that the data was duplicated, I checked it and I do not know if it is the most optimal solution but this was good for me

data_p = pd.read_csv(filename)
data = np.array(data_p.values)
print(data)
    # funcion saveData
    # Retorna el arreglo con el nuevo valor en los indices recibidos.
    # Guarda la información en el archivo
def saveData(indicex,indicey,nuevo_valor):
    data[indicex][indicey] = nuevo_valor
    np.savetxt(filename,data, delimiter=",",fmt="%s",header="Team,Group,Squad Number,Position,Player,Age,Club,Goals")
    return data
saveData(1,1, "Hola")

I hope I have helped you greetings

    
answered by 28.12.2018 в 04:36