'Pandas DF column values get changed but to_csv shows old values

I'm trying to convert some excel files into csv. The follow code worked fine for .xlsx type files but is not working for .xlsm type files:

for i, row in df.iterrows():
    if(row[0] == 'X'): row[0] = 'Y'

csv_file = df.to_csv(name, index=None, header=True)

The df columns get changed but the output to the csv file remains as 'X'



Solution 1:[1]

I'm surprised your solution worked at all; I believe iterrows returns copies of the rows, so modifying those copies shouldn't do anything. A better solution would be to use .replace:

df.iloc[:, 0] = df.iloc[:, 0].replace('X', 'Y')

Or, if you know the name of the column you want to replace X with Y in, use it:

df['column name'] = df['column name'].replace('X', 'Y')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 richardec