python-3.x 如何在pandas中删除行中的空格?

k4ymrczo  于 12个月前  发布在  Python
关注(0)|答案(1)|浏览(125)

我有一个大的Excel文件,我在它的单行看,我想删除文本条目的前导和尾随空格。
代码如下:

df = pd.read_excel(excel_file_name)
layer = df.loc[[layer_index]] # layer is a single row in df and layer_index is an integer
print(layer.iloc[:,37:42])
for col in layer.columns:
    if type(layer[col]) == str:
        layer[col] = layer[col].map(str.strip)
print(layer.iloc[:,37:42])

字符串
第41列包含大量的前导和尾随空格,因此Excel条目在那里类似于Cell 3 ramp。输出为:

Unnamed: 37 Unnamed: 38 Unnamed: 39                           Unnamed: 40 Unnamed: 41
22         NaN         Ga2         NaN                       Cell 3 ramp             NaN
   Unnamed: 37 Unnamed: 38 Unnamed: 39                           Unnamed: 40 Unnamed: 41
22         NaN         Ga2         NaN                       Cell 3 ramp             NaN


但我希望它是这样的,空白被删除:

Unnamed: 37 Unnamed: 38 Unnamed: 39                           Unnamed: 40 Unnamed: 41
22         NaN         Ga2         NaN                       Cell 3 ramp             NaN
   Unnamed: 37 Unnamed: 38 Unnamed: 39  Unnamed: 40 Unnamed: 41
22         NaN         Ga2         NaN  Cell 3 ramp         NaN


为什么我的代码不工作?

yfjy0ee7

yfjy0ee71#

示例

我们需要minimal and reproducible example.

import pandas as pd
df = pd.DataFrame({'col1':['a', 'b', '  c'], 'col2':[1, 2, 3], 'col3':['   ab   ', '  bc', 'd']})

字符串
DF

col1  col2      col3
0    a     1     ab   
1    b     2        bc
2    c     3         d

验证码

这是从所有字符串列中删除白色空格的代码。

cols = df.select_dtypes('object').columns
df[cols] = df[cols].apply(lambda x: x.str.strip())


DF

col1  col2 col3
0    a     1   ab
1    b     2   bc
2    c     3    d

相关问题