Python-如何删除1个以上的空白

Python-如何删除1个以上的空白,python,pandas,Python,Pandas,如下图所示,有大量的空白,包括行的开始、结束和中间。我正在尝试从中间删除这些额外的空格。以下是我尝试过的,但我不断遇到如下错误: testdata = [{'col1': ' Sea Ice Prediction Network . '}, {'col1': ' Movies, Ratings, .... etc.'}, {'col1': 'Iceland, Greenland, Mountains '}, {'col1': ' M

如下图所示,有大量的空白,包括行的开始、结束和中间。我正在尝试从中间删除这些额外的空格。以下是我尝试过的,但我不断遇到如下错误:

testdata = [{'col1': ' Sea Ice   Prediction     Network .    '},
     {'col1': ' Movies, Ratings, ....        etc.'},
     {'col1': 'Iceland, Greenland, Mountains  '},
     {'col1': ' My test file'}]
df = pd.DataFrame(testdata)

' '.join(testdata['col1'].split()) #Error: list indices must be integers or slices, not str

df['col1'].str.lstrip() #list indices must be integers or slices, not str
df['col1'].str.rstrip() #list indices must be integers or slices, not str

 #removes start and end, but not ideal to remove one line at a time. 
' Sea Ice     Prediction Network .    '.lstrip()
' Sea Ice     Prediction Network .    '.rstrip()
我如何删除这个?谢谢

Clean Output: 

'Sea Ice Prediction Network .'
'Movies, Ratings, .... etc.'
'Iceland, Greenland, Mountains '
'My test file'

使用
替换

df.replace({' +':' '},regex=True)
Out[348]: 
                             col1
0   Sea Ice Prediction Network . 
1      Movies, Ratings, .... etc.
2  Iceland, Greenland, Mountains 
3                    My test file

您可以使用
re
模块将字符串中的任何空格替换为单个空格,然后从开头和结尾删除任何内容:

re.sub('\s+', ' ', ' Sea Ice   Prediction     Network .    ').strip()
'Sea Ice Prediction Network .'

之前的空格是否重要?

当您有一个数据帧时,为什么要索引到
测试数据中?