gpt4 book ai didi

python - Pandas 修剪数据帧中的前导和尾随空格

转载 作者:行者123 更新时间:2023-12-04 11:51:23 24 4
gpt4 key购买 nike

开发一个功能,修剪前导和尾随空白。

这是一个简单的示例,但实际文件包含更复杂的行和列。

df=pd.DataFrame([["A b ",2,3],[np.nan,2,3],\
[" random",43,4],[" any txt is possible "," 2 1",22],\
["",23,99],[" help ",23,np.nan]],columns=['A','B','C'])

结果应该消除所有前导和尾随空格,但保留文本之间的空间。
df=pd.DataFrame([["A b",2,3],[np.nan,2,3],\
["random",43,4],["any txt is possible","2 1",22],\
["",23,99],["help",23,np.nan]],columns=['A','B','C'])

请注意,该功能需要涵盖所有可能的情况。
谢谢你

最佳答案

我认为需要检查值是否为字符串,因为列中的混合值 - 带有字符串的数字以及每个字符串调用 strip :

df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x)
print (df)
A B C
0 A b 2 3.0
1 NaN 2 3.0
2 random 43 4.0
3 any txt is possible 2 1 22.0
4 23 99.0
5 help 23 NaN

如果列具有相同的数据类型,则不会得到 NaN就像在您的示例中一样,列 B 中的数值:
cols = df.select_dtypes(['object']).columns
df[cols] = df[cols].apply(lambda x: x.str.strip())
print (df)
A B C
0 A b NaN 3.0
1 NaN NaN 3.0
2 random NaN 4.0
3 any txt is possible 2 1 22.0
4 NaN 99.0
5 help NaN NaN

关于python - Pandas 修剪数据帧中的前导和尾随空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49551336/

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