为了账号安全,请及时绑定邮箱和手机立即绑定

使用熊猫替换 xlsx 文件中的值

使用熊猫替换 xlsx 文件中的值

梵蒂冈之花 2023-03-08 15:55:07
我查看了其他示例并实施了它们,但没有得到正确的结果。我有几个看起来像这样的数据框Player_Name   0 J.T. PostonPlayer_Name    0 J.T. Poston我正在尝试更改名称以匹配我拥有的另一个 excel 文件,因此我没有使用 excel 索引手动执行此操作。这是我的代码。import jsonimport pandas as pdimport osyear = 2018path_to_excel = '/Users/aus10/Desktop/PGA/PGA_Tour_Stats/Tournament_Results_Excel/'+str(year)+''excel_files = [pos_json for pos_json in os.listdir(path_to_excel) if pos_json.endswith('.xlsx')]for files in excel_files:    df = pd.read_excel('/Users/aus10/Desktop/PGA/PGA_Tour_Stats/Tournament_Results_Excel/'+str(year)+'/'+files+'')    df['Player_Name'].replace(to_replace='J.T. Poston', value='JT Poston')    print(df)    writer = pd.ExcelWriter('/Users/aus10/Desktop/PGA/PGA_Tour_Stats/Tournament_Results_Excel/'+str(year)+'/'+files+'', engine='xlsxwriter')    df.to_excel(writer, sheet_name='Sheet1', index=False)    df.style.set_properties(**{'text-align': 'center'})    pd.set_option('display.max_colwidth', 100)    pd.set_option('display.width', 1000)    writer.save()但是,当我在运行代码后打开 excel 文件时,名称没有改变。.xlsx因为我使用的是文件而不是,是否有我遗漏的东西或我需要的特定方式.csv?
查看完整描述

1 回答

?
茅侃侃

TA贡献1842条经验 获得超21个赞

这种情况下的重要参数是inplace。检查此问题或直接在replace的文档中找到有关此主题的注释。

您应该足以使用此更新:

df['Player_Name'] = df['Player_Name'].replace(to_replace='J.T. Poston', value='JT Poston')

否则,您正在对副本进行替换,而不是对原始数据框进行替换。

选项 withinplace=True也应该有效:

df.replace(to_replace='J.T. Poston', value='JT Poston', inplace=True)


查看完整回答
反对 回复 2023-03-08
  • 1 回答
  • 0 关注
  • 79 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号