【问题标题】:How to empty string in pandas [duplicate]如何在熊猫中清空字符串[重复]
【发布时间】:2021-04-01 16:03:05
【问题描述】:

所以,我一直在使用 python 中的 pandas,我从外部系统中提取数据,每列末尾有很多空格。我想在每个系列上使用带有代码的 str.strip() 方法:

Data["DESCRIPTION"] =  Data["DESCRIPTION"].str.strip()

它基本上完成了它的工作,但我注意到当我使用检查数据框的属性时遇到一个问题,如果在一个值中只有空格而没有任何文本,那么它是空的,但它不会将该标量转换为 null :

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 18028 entries, 0 to 18027
Data columns (total 11 columns):
 #   Column          Non-Null Count  Dtype 
---  ------          --------------  ----- 
 0   VIN             18028 non-null  object
 1   DESCRIPTION     18028 non-null  object
 2   DESCRIPTION 2   18028 non-null  object
 3   ENGINE          18023 non-null  object
 4   TRANSMISSION    18028 non-null  object
 5   PAINT           18028 non-null  object
 6   EXT_COLOR_CODE  18028 non-null  object
 7   EXT_COLOR_DESC  18028 non-null  object
 8   INT_COLOR_DESC  18028 non-null  object
 9   COUNTRY         18028 non-null  object
 10  PROD_DATE       18028 non-null  object
dtypes: object(11)
memory usage: 1.5+ MB

如果字符串为空,则检查条件:

Data['DESCRIPTION 2'] == ""


    0        True
    1        True
    2        True
    3        True
    4        True
             ... 
    18023    True
    18024    True
    18025    True
    18026    True
    18027    True
    Name: DESCRIPTION 2, Length: 18028, dtype: bool

我怎么可能将所有这些都转换为 null 以便我可以使用 dropna() 函数删除它们?

如有任何建议,我将不胜感激。

【问题讨论】:

  • Data["DESCRIPTION"] = Data["DESCRIPTION"].str.strip().replace('', np.nan)

标签: python pandas


【解决方案1】:

要删除尾随空格并将空字符串或记录替换为 Nan,请运行以下命令。

Data["DESCRIPTION"].str.strip().replace(r'^\s*$', np.nan, regex=True)

请参考本页Replacing blank values (white space) with NaN in pandas

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-24
    • 2018-11-06
    • 2020-12-21
    • 2019-07-25
    • 2015-01-26
    • 2017-08-02
    • 2020-04-08
    相关资源
    最近更新 更多