【问题标题】:Pandas strip function removes numeric values as wellPandas strip 函数也会删除数值
【发布时间】:2019-06-13 03:50:25
【问题描述】:

我有一个可以从下面的代码生成的数据框

data_file= pd.DataFrame({'studyid':[1,2,3],'age_interview': [' 56','57 ','55'],'ethnicity': ['Chinese','Indian','European'],'Marital_status': ['Single','Married','Widowed'],'Smoke_status':['Yes','No','No']}) 

创建上述数据框后,我将其融化并应用 strip 函数

obs = data_file.melt('studyid', value_name='valuestring').sort_values('studyid')
obs['valuestring'].str.strip()

虽然它在示例数据中运行良好,但在实际数据中它也会删除数值。我遵循与上面相同的代码,但只是数据不同。

请找到strip函数前后的截图

“obs['valuestring'].str.strip()”之前的输出

在“obs['valuestring'].str.strip()”之后输出

如何防止数值被删除?

【问题讨论】:

    标签: python python-3.x pandas dataframe strip


    【解决方案1】:

    您的列似乎包含混合整数和字符串。这是一个可重现的示例:

    s = pd.Series([1, np.nan, 'abc ', 2.0, '  def '])
    s.str.strip()
    
    0    NaN
    1    NaN
    2    abc
    3    NaN
    4    def
    dtype: object
    

    如果该值不是字符串,则将其隐式处理为 NaN。

    解决方案是在调用strip之前将列及其所有值转换为字符串。

    s.astype(str).str.strip()
    
    0      1
    1    nan
    2    abc
    3    2.0
    4    def
    dtype: object
    

    在你的情况下,那是

    obs['valuestring'] = obs['valuestring'].astype(str).str.strip()
    

    请注意,如果您想保留 NaN,请在末尾使用 mask

    s.astype(str).str.strip().mask(s.isna())
    
    0      1
    1    NaN
    2    abc
    3    2.0
    4    def
    dtype: object
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-05
      • 1970-01-01
      相关资源
      最近更新 更多