my df的索引是公司名稱的字符串。EgWells Fargo
有時會有多余的空格in-between我只想將單詞轉換為單個空格。我嘗試了下面的方法,但出現了錯誤。
**TypeError: expected string or bytes-like object**
df.index=re.sub(' +', ' ', df.index.astype('str').str.strip())
**AttributeError: 'Index' object has no attribute 'apply'**
df.index=df.index.astype('str').str.strip().apply(lambda x: re.sub(' +', ' ', x))
Input df
| Revenue |
Wells Fargo | 1 |
Bank of American| 3 |
Desired output
| Revenue |
Wells Fargo | 1 |
Bank of American| 3 |
在第一次嘗試中,您試圖將Pandas Index個字符串傳遞給
re.sub
,它接受一個字符串。如果公司名稱存儲為數據框列,
apply
將起作用。但是,正如錯誤消息所說,apply
沒有為索引實現。