剥离/修剪数据框的所有字符串 [英] Strip / trim all strings of a dataframe

查看:50
本文介绍了剥离/修剪数据框的所有字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python/pandas中清理多类型数据框的值,我想对字符串进行修剪.我目前正在按照两条说明进行操作:

Cleaning the values of a multitype data frame in python/pandas, I want to trim the strings. I am currently doing it in two instructions :

import pandas as pd

df = pd.DataFrame([['  a  ', 10], ['  c  ', 5]])

df.replace('^\s+', '', regex=True, inplace=True) #front
df.replace('\s+$', '', regex=True, inplace=True) #end

df.values

这很慢,我可以改善什么?

This is quite slow, what could I improve ?

推荐答案

您可以使用

You can use DataFrame.select_dtypes to select string columns and then apply function str.strip.

注意:值不能像dictslists那样是types,因为它们的dtypesobject.

Notice: Values cannot be types like dicts or lists, because their dtypes is object.

df_obj = df.select_dtypes(['object'])
print (df_obj)
0    a  
1    c  

df[df_obj.columns] = df_obj.apply(lambda x: x.str.strip())
print (df)

   0   1
0  a  10
1  c   5

但是,如果只有几列,请使用 str.strip :

But if there are only a few columns use str.strip:

df[0] = df[0].str.strip()

这篇关于剥离/修剪数据框的所有字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆