Kinformationist
Kinformationist

Reputation: 324

Pandas- How can I eliminate trailing whitespace in the index

df = pd.DataFrame({'A' : ['one', 'two three', 'f four   ', 'three '], 'B': [10,20,30,40]})

df = df.set_index('A')

Here is what the df needs to be:

            B
A   
one        10
two three  20
f four     30
three      40

In the final data frame, the spaces in indices should be removed if they are trailing. If they are anywhere else, they need to remain. So the trailing spaces in 'three ' and 'f four ' need to be deleted.

Upvotes: 3

Views: 6968

Answers (1)

jezrael
jezrael

Reputation: 863291

I think you need strip:

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']

Another solution is use rename:

df = df.rename(lambda x: x.strip())

Upvotes: 8

Related Questions