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

时间:2020-07-15 13:38:03

标签: python excel pandas

我看了其他示例并实现了它们,但是我没有得到正确的结果。 我有几个看起来像这样的数据框

Player_Name 

  0 J.T. Poston

Player_Name
  
  0 J.T. Poston

我正在尝试更改名称以匹配我拥有的另一个excel文件,所以我没有使用excel索引手动进行操作。这是我的代码。

import json
import pandas as pd
import os

year = 2018

path_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 个答案:

答案 0 :(得分:1)

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

使用此更新应该足够了:

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

否则,您将在副本上执行替换操作,而不是原始数据帧。

带有inplace=True的选项也应该有效:

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