亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

誰能建議使用 re.sub() 在 pandas 數據框列名中替換字符串?

誰能建議使用 re.sub() 在 pandas 數據框列名中替換字符串?

慕姐8265434 2022-11-01 16:11:15
我對有效數據框 df 有以下問題,該數據框在列名中包含諸如“_”、“”、“?”和“-”之類的字符。數據框是從第三方 csv 導入的。我需要擺脫這些字符,所以:import pandas as pdimport re. . . 定義 df 。. .dfr = [(' ', '_'), ('?', ''), ('/', '_'), ('-', '_')]# df.columns = df.columns.str.replace(' ', '_') | *these four*   # df.columns = df.columns.str.replace('?', '')  | *lines are*# df.columns = df.columns.str.replace('/', '_') | *my original*# df.columns = df.columns.str.replace('-', '_') | *functioning code*for o, n in dfr:    df.columns = re.sub(o, n, df.columns.str)這會產生以下錯誤:Traceback (most recent call last):  File "<input>", line 33, in <module>  File "C:\Users\andyt\anaconda3\envs\Property\lib\re.py", line 208, in sub    return _compile(pattern, flags).sub(repl, string, count)TypeError: expected string or bytes-like object有人可以幫忙嗎?響應@sammywemmy 的列名:c = ['Postcode', 'In Use?', 'Latitude', 'Longitude', 'Easting', 'Northing', 'Grid Ref', 'County',                          'District', 'Ward', 'Country', 'Constituency', 'Introduced', 'Terminated', 'Parish',                          'National Park', 'Population', 'Households', 'Built up area', 'Built up sub-division',                          'Lower layer super output area', 'Rural/urban', 'Region', 'Altitude', 'London zone',                          'Local authority', 'Middle layer super output area', 'Index of Multiple Deprivation',                          'Quality', 'User Type', 'Last updated', 'Nearest station', 'Distance to station',                          'Police force', 'Water company', 'Plus Code', 'Average Income']更新以響應@AMC@AMC 還問我從那個錯誤中理解了什么......答案是re.sub模塊似乎想要一個字符串作為第三個參數傳遞(我已經通過單獨分配o = ' '和n = '_'代替字典分配來調試它dfr = ...并且錯誤仍然存在)但我看不到'df. columns.str' 可以作為字符串 indf.columns = df.columns.str.replace(' ', '_')但不能在df.columns = re.sub(o, n, df.columns.str).
查看完整描述

1 回答

?
長風秋雁

TA貢獻1757條經驗 獲得超7個贊

只需更換您的線路:

df.columns = re.sub(o, n, df.columns.str)

df.columns = df.columns.str.replace(o,n)

你很好!


查看完整回答
反對 回復 2022-11-01
  • 1 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號