gau*_*207 4 python numpy pandas
我正在研究一个问题集,其中 Pandas 数据框中有很多列,并且其中许多列都有尾随空格。我的问题是,有没有更好的方法来删除这些空格,而不是创建一个动态字符串(我们将列名作为变量传递并附加 astrip()到它),然后对每个列执行它。
如果没有示例,则不完全清楚您想要完成什么,但也许以下内容会有所帮助:
import pandas as pd
df = pd.DataFrame({'A ': [1, 2], 'B ': [4, 5], 'C': [8,9]})
Run Code Online (Sandbox Code Playgroud)
列标题确实有尾随空格:
df.columns
Index([u'A ', u'B ', u'C'], dtype='object')
Run Code Online (Sandbox Code Playgroud)
现在您可以使用map并strip删除它们:
df.columns = df.columns.map(lambda x: x.strip())
Run Code Online (Sandbox Code Playgroud)
或者替代地
df.columns = df.columns.map(str.strip)
Run Code Online (Sandbox Code Playgroud)
或者简单地(这应该是首选)
df.columns = df.columns.str.strip()
Run Code Online (Sandbox Code Playgroud)
如果你现在打电话
df.columns
Run Code Online (Sandbox Code Playgroud)
它产生
Index([u'A', u'B', u'C'], dtype='object')
Run Code Online (Sandbox Code Playgroud)
如果它是关于值而不是标题,您还可以使用applymap:
df = pd.DataFrame({'A': ['1', '2 '], 'B': ['4 ', '5 '], 'C': ['8 ','9']})
A B C
0 1 4 8
1 2 5 9
Run Code Online (Sandbox Code Playgroud)
然后下面的代码去掉了尾随的空格:
df.applymap(lambda x: x.strip())
Run Code Online (Sandbox Code Playgroud)
或者(这是更好的选择):
df.applymap(str.strip)
A B C
0 1 4 8
1 2 5 9
Run Code Online (Sandbox Code Playgroud)
注意:这假设您的列中只有字符串。您还可以查看此链接。
| 归档时间: |
|
| 查看次数: |
10363 次 |
| 最近记录: |