繁体   English   中英

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

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

当单元格是特定名称时,我正在尝试编写一个脚本来更改名为“ticker”的列的单元格。 例如,对于代码列中的所有“BRK.B”单元格,我想将它们更改为“BRK-B”。

代码:

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

这并没有改变文件中的任何内容,我不知道为什么。 我会很感激一些帮助。

iterrows()的文档中它说

你永远不应该修改你正在迭代的东西。 这不能保证在所有情况下都有效。 根据数据类型,迭代器返回一个副本而不是一个视图,写入它不会有任何效果。

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

看起来像这样

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