📜  python - 删除单元格中的空白空间 - Python (1)

📅  最后修改于: 2023-12-03 15:18:52.177000             🧑  作者: Mango

Python - 删除单元格中的空白空间

在进行数据处理和分析时,我们经常需要删除单元格中的空白空间,以便更好地处理和分析数据。在Python中,我们可以使用字符串的strip()方法来删除空白空间。

strip()方法

strip()方法可以去掉字符串开头和结尾的空格、制表符、换行符等空白字符。

string = "  Hello world  "
print(string.strip()) #output: "Hello world"
对单元格应用strip()方法

要对pandas DataFrame中的单元格应用strip()方法,我们可以使用applymap()方法。

import pandas as pd

# create sample dataframe
df = pd.DataFrame({'A': ['     apple    ', '   banana ', 'orange  ', '  cherry']})

# apply strip() method on all elements of the dataframe
df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x)

print(df)

输出:

| | A | |---:|:--------| | 0 | apple | | 1 | banana | | 2 | orange | | 3 | cherry |

结论

在Python中,strip()方法是一个很方便的用于删除单元格中的空白空间的字符串方法。当我们需要处理和分析数据时,我们可以将其应用于pandas DataFrame中的单元格。