You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pandas(Python)更新CSV中用户指定的单元格

解决Pandas修改CSV单元格后无法保存的问题

我来帮你排查下代码里的问题,你遇到的CSV文件没更新的核心原因是修改了内存中的DataFrame但没有将其写回原文件,另外还有几个小细节会影响功能正确性,我来逐一说明并给出修正后的代码:

原代码的核心问题

  • 未将修改后的数据写入CSV:你只修改了内存里的df5对象,但从来没把更改保存到磁盘的statedata.csv文件中,这是最关键的疏漏。
  • replace方法存在误改风险:replace({pop_pop: updated_pop}, regex=True)会替换整个DataFrame中所有等于旧人口值的内容,而不是仅修改目标州的单元格,很可能会误改其他州的相同数字。
  • 递归调用易引发栈溢出:函数末尾递归调用update_population(),如果用户多次操作会导致递归深度过大报错,用循环更安全。
  • 更新后打印的仍是旧值:最后打印时用了pop_pop(旧人口数),没有展示真正的更新结果。

修正后的代码

import pandas as pd

state_names = ["Alaska", "Alabama", "Arkansas", "American Samoa", "Arizona", "California", "Colorado", "Connecticut", "District ", "of Columbia", "Delaware", "Florida", "Georgia", "Guam", "Hawaii", "Iowa", "Idaho", "Illinois", "Indiana", "Kansas", "Kentucky", "Louisiana", "Massachusetts", "Maryland", "Maine", "Michigan", "Minnesota", "Missouri", "Mississippi", "Montana", "North Carolina", "North Dakota", "Nebraska", "New Hampshire", "New Jersey", "New Mexico", "Nevada", "New York", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Puerto Rico", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Virginia", "Virgin Islands", "Vermont", "Washington", "Wisconsin", "West Virginia", "Wyoming"]

def update_population():
    # 读取CSV文件到DataFrame
    df5 = pd.read_csv("statedata.csv", encoding='UTF8')
    
    while True:
        update_pop = input("\nWhich state would you like to update? (输入'quit'退出): ")
        
        # 增加退出逻辑,避免无限循环
        if update_pop.lower() == 'quit':
            print("退出程序")
            break
            
        if update_pop not in state_names:
            print("无效的州名,请重新输入")
            continue
            
        # 精准定位目标州的行索引
        state_index = df5[df5['State'] == update_pop].index[0]
        current_pop = df5.loc[state_index, 'Population']
        
        print(f"\nThe current population of {update_pop} is: {current_pop}")
        
        # 处理非整数输入的异常情况
        try:
            updated_pop = int(input(f"\nPlease enter the new population value for {update_pop}: "))
        except ValueError:
            print("请输入有效的整数数值")
            continue
            
        # 直接修改目标单元格,避免误改其他数据
        df5.loc[state_index, 'Population'] = updated_pop
        
        # 将修改后的DataFrame写回CSV文件,index=False避免写入额外索引列
        df5.to_csv("statedata.csv", encoding='UTF8', index=False)
        
        # 读取并打印最新的人口数值
        new_pop = df5.loc[state_index, 'Population']
        print(f"\nThe updated population of {update_pop} is: {new_pop}")

# 启动更新函数
update_population()

关键修改说明

  1. 添加文件持久化操作:用df5.to_csv()把修改后的DataFrame写回原文件,index=False防止Pandas自动添加的索引列污染CSV内容。
  2. 精准定位修改:通过df5.loc[state_index, 'Population']直接定位目标单元格,彻底避免误改其他数据的风险。
  3. 替换递归为循环:用while True实现多次操作逻辑,配合quit退出条件,避免递归栈溢出问题。
  4. 增强输入健壮性:捕获用户输入非整数的异常,提升程序容错性。
  5. 修正打印逻辑:从修改后的DataFrame中读取最新值打印,确保展示结果准确。

内容的提问来源于stack exchange,提问作者VargThorsolf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 01:07:32