我的 df 的索引是公司名稱的字串。例如Wells Fargo
有時我想轉換為單個空格的單詞之間有多余的空格。我嘗試了以下但出現錯誤。
**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))
輸入 df
| Revenue |
Wells Fargo | 1 |
Bank of American| 3 |
期望輸出
| Revenue |
Wells Fargo | 1 |
Bank of American| 3 |
uj5u.com熱心網友回復:
df.index = df.index.str.replace(r'\s ', ' ', regex=True).str.strip()
在您的第一次嘗試中,您試圖將字串的 Pandas 索引傳遞給re.sub,它接受一個字串。
apply如果將公司名稱存盤為資料框列,則會起作用。但是,正如錯誤訊息所說,apply沒有為索引實作。
uj5u.com熱心網友回復:
在字串上使用 str.split() ,然后在索引上使用 df.rename 。請參閱下面的每個步驟。
import pandas as pd
# making your df
d = {'index':['Wells Fargo'], 'col1':[123], 'col2':[123]}
df = pd.DataFrame(d)
df = df.set_index('index')
# get list of index strings
index_str_list = [strings for strings in df.index]
# format spaces and append to new list
new_list = []
for i in index_str_list:
s1,s2 = i.split()
s = "{:6}{:}".format(s1,s2) # set your distance
new_list.append(s)
# change index value
for old,new in zip(index_str_list, new_list):
df.rename(index={old:new}, inplace=True)
print(df)
Output:
col1 col2
index
Wells Fargo 123 123
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/401826.html
上一篇:PythonPyrebase錯誤:TypeError:'set'物件不可下標
下一篇:努力使用django顯示影像
