我查看了其他示例并實(shí)施了它們,但沒(méi)有得到正確的結(jié)果。我有幾個(gè)看起來(lái)像這樣的數(shù)據(jù)框Player_Name 0 J.T. PostonPlayer_Name 0 J.T. Poston我正在嘗試更改名稱(chēng)以匹配我擁有的另一個(gè) excel 文件,因此我沒(méi)有使用 excel 索引手動(dòng)執(zhí)行此操作。這是我的代碼。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()但是,當(dāng)我在運(yùn)行代碼后打開(kāi) excel 文件時(shí),名稱(chēng)沒(méi)有改變。.xlsx因?yàn)槲沂褂玫氖俏募皇?,是否有我遺漏的東西或我需要的特定方式.csv?
1 回答

茅侃侃
TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超21個(gè)贊
這種情況下的重要參數(shù)是inplace
。檢查此問(wèn)題或直接在replace的文檔中找到有關(guān)此主題的注釋。
您應(yīng)該足以使用此更新:
df['Player_Name'] = df['Player_Name'].replace(to_replace='J.T. Poston', value='JT Poston')
否則,您正在對(duì)副本進(jìn)行替換,而不是對(duì)原始數(shù)據(jù)框進(jìn)行替換。
選項(xiàng) withinplace=True
也應(yīng)該有效:
df.replace(to_replace='J.T. Poston', value='JT Poston', inplace=True)
添加回答
舉報(bào)
0/150
提交
取消