简体   繁体   English

如何使用 iterrows() 更改 CSV 文件中一行中单元格的值?

[英]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.当单元格是特定名称时,我正在尝试编写一个脚本来更改名为“ticker”的列的单元格。 For example, for all the cells that are 'BRK.B' in the ticker column, I want to change them to 'BRK-B' instead.例如,对于代码列中的所有“BRK.B”单元格,我想将它们更改为“BRK-B”。

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 saysiterrows()的文档中它说

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 .相反,要修改列中的所有值,您应该使用apply()方法并定义 function 来处理将BRK.B更改为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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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