Pandas 去除空格

Pandas 去除空格

在本文中,我们将介绍如何使用Pandas在DataFrame中去除空格。

阅读更多:Pandas 教程

1. strip()函数

Pandas的strip()函数用于去除DataFrame中字符串的前后空格。具体用法为:

df['column'] = df['column'].str.strip()

其中,df['column']表示DataFrame中的一列,可以根据需要进行更换。以下是一个简单的示例:

import pandas as pd

df = pd.DataFrame({'A': [' John', 'Jane ', ' Jack ', 'Jill   '], 'B': [1,2,3,4]})
print(df)

df['A'] = df['A'].str.strip()
print(df)

输出结果为:

        A  B
0    John  1
1   Jane   2
2   Jack   3
3  Jill    4

      A  B
0  John  1
1  Jane  2
2  Jack  3
3  Jill  4

2. replace()函数

除了使用strip()函数,我们还可以使用replace()函数去除DataFrame中的空格。具体用法为:

df['column'] = df['column'].str.replace(' ','')

其中,df['column']表示DataFrame中的一列,可以根据需要进行更换。以下是一个示例:

import pandas as pd

df = pd.DataFrame({'A': [' John', 'Jane ', ' Jack ', 'Jill   '], 'B': [1,2,3,4]})
print(df)

df['A'] = df['A'].str.replace(' ','')
print(df)

输出结果为:

        A  B
0    John  1
1   Jane   2
2   Jack   3
3  Jill    4

      A  B
0  John  1
1  Jane  2
2  Jack  3
3  Jill  4

3. apply()函数

有时候,我们需要去除DataFrame中所有列的空格。此时,可以使用apply()函数结合strip()或replace()函数来实现。

使用apply()函数实现strip()函数:

df = df.apply(lambda x: x.str.strip() if x.dtype == "object" else x)

使用apply()函数实现replace()函数:

df = df.apply(lambda x: x.str.replace(' ', '') if x.dtype == "object" else x)

以下是一个示例:

import pandas as pd

df = pd.DataFrame({'A': [' John', 'Jane ', ' Jack ', 'Jill   '], 'B': [1,2,3,4], 'C': [' Hello ', ' World    ', 'Python   ', 'Pandas']})
print(df)

df = df.apply(lambda x: x.str.strip() if x.dtype == "object" else x)
print(df)

df = df.apply(lambda x: x.str.replace(' ', '') if x.dtype == "object" else x)
print(df)

输出结果为:

        A  B            C
0    John  1       Hello 
1   Jane   2     World    
2   Jack   3     Python   
3  Jill    4       Pandas

      A  B        C
0  John  1    Hello
1  Jane  2   World
2  Jack  3  Python
3  Jill  4  Pandas

     A  B       C
0  John  1   Hello
1  Jane  2   World
2  Jack  3  Python
3  Jill  4  Pandas

总结

本文介绍了Pandas中去除空格的几种方法,包括strip()函数、replace()函数和apply()函数的结合使用。在实际应用中,根据需要选择合适的方法可以提高数据处理的效率和准确性。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程