简体   繁体   中英

How to change the value of a cell in a row in a CSV file using iterrows()?

I'm trying to write a script to change the cells of a column named 'ticker', when the cell is a specific name. For example, for all the cells that are 'BRK.B' in the ticker column, I want to change them to 'BRK-B' instead.

Code:

company_input = input('What company do you want to change the value of?')
company_input.upper()
print(f'Company chosen is: {company_input}')

company_change = input('What would you like to change the value to?')
company_change.upper()
# For SF1 file
for ticker, row in sf1.iterrows():
    row['ticker'] = company_input
    row['ticker'] = company_change

This isn't changing anything in the file and I'm not sure why. I'd appreciate some help.

In the documentation of iterrows() it says

You should never modify something you are iterating over. This is not guaranteed to work in all cases. Depending on the data types, the iterator returns a copy and not a view, and writing to it will have no effect.

Instead, to modify all the values in a column, you should use the apply() method and define a function to handle changing BRK.B to BRK-B .

That would look something like this

def change_cell(x): #? x is the original value
    return x.replace(".", "-") #? The return value will be whatever the cell is modified into

df['ticker'] = df['ticker'].apply(change_cell)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM