gpt4 book ai didi

python - 从 Pandas 中的所有列值中去除空间

转载 作者:行者123 更新时间:2023-12-05 01:19:04 24 4
gpt4 key购买 nike

我正在处理一个问题集,其中我们在 Pandas 数据框中有很多列,其中许多列都有尾随空格。我的问题是,有没有更好的方法来删除这些空格而不是创建一个动态字符串(我们将列名作为变量传递并附加一个 strip() 到它)然后为每个执行它专栏。

最佳答案

如果没有示例,您将无法完全清楚您想要完成什么,但以下内容可能会有所帮助:

import pandas as pd

df = pd.DataFrame({'A ': [1, 2], 'B ': [4, 5], 'C': [8,9]})

列标题确实有尾随空格:

df.columns
Index([u'A ', u'B ', u'C'], dtype='object')

现在您可以使用 mapstrip 来摆脱它们:

df.columns = df.columns.map(lambda x: x.strip())

或者替代地

df.columns = df.columns.map(str.strip)

或简单地(这应该是首选)

df.columns = df.columns.str.strip()

如果你现在调用

df.columns

它产生

Index([u'A', u'B', u'C'], dtype='object')

如果是关于值而不是标题,你也可以使用applymap:

df = pd.DataFrame({'A': ['1', '2  '], 'B': ['4 ', '5 '], 'C': ['8 ','9']})

A B C
0 1 4 8
1 2 5 9

然后下面的代码去掉了尾随的空格:

df.applymap(lambda x: x.strip())

或者(这是更好的选择):

df.applymap(str.strip)

A B C
0 1 4 8
1 2 5 9

注意:这假设您的列中只有字符串。您也可以查看 this link .

关于python - 从 Pandas 中的所有列值中去除空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42229368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com