【问题标题】:Get specific string in a column and then change it Pandas获取列中的特定字符串,然后更改它 Pandas
【发布时间】:2020-06-07 23:42:03
【问题描述】:

我的数据集有一列包含负数(-14、-16、...),但有时数据集仅包含“-”而没有数字。如果发生这种情况,我不会将其更改为 0,然后将 dtype 更改为 int64。

我用 df['Level'].str.contains('-') 尝试过,但这适用于所有单元格。

【问题讨论】:

  • 有什么问题?将其转换为整数列?

标签: python pandas


【解决方案1】:

使用Series.replace,然后使用Series.astype

例如:

>>> df = pd.DataFrame({'Level':[1,-2,'-',2]})
>>> df
    a
0   1
1  -2
2   -
3   2
>>> df['Level'] = df.Level.replace('-',0).astype('int64')
>>> df
   Level
0      1
1     -2
2      0
3      2
>>> df['Level'].dtypes
dtype('int64')

【讨论】:

    【解决方案2】:

    pd.to_numericerrors='coerce'fillna 是您最安全的选择,而且您的列也将转换为数字:

    >>> df = pd.DataFrame({'Level':['-16', '-14', '-']})
    >>> df
      Level
    0   -16
    1   -14
    2     -
    >>> df['Level'] = pd.to_numeric(df['Level'], errors='coerce').fillna(0)
    >>> df
       Level
    0  -16.0
    1  -14.0
    2    0.0
    

    【讨论】:

      【解决方案3】:

      使用np.where

      例如:

      df['Level'] = np.where(df['Level']=='-', 0, df['Level'])
      

      【讨论】:

        猜你喜欢
        • 2019-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-19
        • 2020-07-24
        • 1970-01-01
        • 2012-11-12
        相关资源
        最近更新 更多