Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫-如何消除索引中的尾随空格_Python_String_Pandas_Removing Whitespace - Fatal编程技术网

Python 熊猫-如何消除索引中的尾随空格

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所需要的:

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())