Python 熊猫-如何消除索引中的尾随空格
以下是df所需要的:Python 熊猫-如何消除索引中的尾随空格,python,string,pandas,removing-whitespace,Python,String,Pandas,Removing Whitespace,以下是df所需要的: df = pd.DataFrame({'A' : ['one', 'two three', 'f four ', 'three '], 'B': [10,20,30,40]}) df = df.set_index('A') 在最后一个数据帧中,如果索引中的空格是尾随的,则应将其删除。如果他们在其他地方,他们需要留下来。因此,需要删除'three'和'f4'中的尾随空格 我认为您需要: 另一种解决方案是使用重命名: print (df.index.tolist())
df = pd.DataFrame({'A' : ['one', 'two three', 'f four ', 'three '], 'B': [10,20,30,40]})
df = df.set_index('A')
在最后一个数据帧中,如果索引中的空格是尾随的,则应将其删除。如果他们在其他地方,他们需要留下来。因此,需要删除'three'和'f4'中的尾随空格 我认为您需要:
另一种解决方案是使用重命名:
print (df.index.tolist())
['one', 'two three', 'f four ', 'three ']
df.index = df.index.str.strip()
print (df)
B
A
one 10
two three 20
f four 30
three 40
print (df.index.tolist())
['one', 'two three', 'f four', 'three']
print (df.index.tolist())
['one', 'two three', 'f four ', 'three ']
df.index = df.index.str.strip()
print (df)
B
A
one 10
two three 20
f four 30
three 40
print (df.index.tolist())
['one', 'two three', 'f four', 'three']
df = df.rename(lambda x: x.strip())