我對有效數據框 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)
你很好!
添加回答
舉報
0/150
提交
取消
