简体   繁体   English

从整个 DataFrame 中删除空格

[英]Remove white space from entire DataFrame

i have a dataframe, 22 columns and 65 rows.我有一个 dataframe,22 列和 65 行。 The data comes in from csv file.数据来自 csv 文件。 Each of the values with dataframe has an extra unwanted whitespace.每个带有 dataframe 的值都有一个额外的不需要的空格。 So if i do a loop on 'Year' column with a Len() i get因此,如果我使用 Len() 在“年”列上进行循环,我会得到

2019  5
2019  5
2018  5
...

this 1 extra whitespace appears throughout DF in every value.这 1 个额外的空格出现在整个 DF 的每个值中。 I tried running a.strip() on DF but no attribute exists我尝试在 DF 上运行 a.strip() 但不存在属性

i tried a 'for each df[column].str.strip() but there are various data types in each column... dtypes: float64(6), int64(4), object(14), so this errors.我为每个 df[column].str.strip() 尝试了一个 ' 但每列中都有各种数据类型... dtypes:float64(6)、int64(4)、object(14),所以这个错误。

any ideas on how to apply a function for entire dataframe, and if so, what function/method?关于如何为整个 dataframe 应用 function 的任何想法,如果是这样,什么功能/方法? if not what is best way to handle?如果不是,最好的处理方法是什么?

you should use apply() function in order to do this:您应该使用apply() function 来执行此操作:

df['Year'] = df['Year'].apply(lambda x:x.strip() )

you can apply this function on each column separately:您可以分别在每列上应用此 function:

for column in df.columns:
    df[column] = df[column].apply(lambda x:x.strip() )

Handle the error:处理错误:

for col in df.columns:
    try:
        df[col] = df[col].str.strip()
    except AttributeError:
        pass

Normally, I'd say select the object dtypes, but that can still be problematic if the data are messy enough to store numeric data in an object container.通常,我会说 select 和object dtypes,但如果数据足够混乱以将数字数据存储在 object 容器中,这仍然会出现问题。

import pandas as pd

df = pd.DataFrame({'foo': [1, 2, 3], 'bar': ['seven ']*3})
df['foo2'] = df.foo.astype(object)

for col in df.select_dtypes('object'):
    df[col] = df[col].str.strip()
#AttributeError: Can only use .str accessor with string values!

Try this:尝试这个:

for column in df.columns:
    df[column] = df[column].apply(lambda x: str(x).replace('  ', ' '))

Why not try this?为什么不试试这个?

for column in df.columns:
    df[column] = df[column].apply(lambda x: str(x).strip())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM