【问题标题】:Remove rows where column value type is string Pandas删除列值类型为字符串 Pandas 的行
【发布时间】:2015-01-02 11:41:50
【问题描述】:

我有一个熊猫数据框。我的专栏之一应该只是花车。当我尝试将该列转换为浮点数时,我被提醒那里有字符串。我想删除此列中的值为字符串的所有行...

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    我的专栏之一应该只是浮动。我想删除所有行 其中此列中的值是字符串

    您可以通过pd.to_numeric 将您的系列转换为数字,然后使用pd.Series.notnull。转换为float 是一个单独的步骤,以避免您的系列恢复为object dtype。

    # Data from @EdChum
    
    df = pd.DataFrame({'a': [0.1, 0.5, 'jasdh', 9.0]})
    
    res = df[pd.to_numeric(df['a'], errors='coerce').notnull()]
    res['a'] = res['a'].astype(float)
    
    print(res)
    
         a
    0  0.1
    1  0.5
    3  9.0
    

    【讨论】:

      【解决方案2】:

      假设您的数据框是df,并且您希望确保数据框的一列中的所有数据都是特定pandas dtype中的数字,例如float

      df[df.columns[n]] = df[df.columns[n]].apply(pd.to_numeric, errors='coerce').fillna(0).astype(float).dropna()
      

      【讨论】:

        【解决方案3】:

        使用convert_objects 和参数convert_numeric=True 这会将任何非数值强制转换为NaN

        In [24]:
        
        df = pd.DataFrame({'a': [0.1,0.5,'jasdh', 9.0]})
        df
        Out[24]:
               a
        0    0.1
        1    0.5
        2  jasdh
        3      9
        In [27]:
        
        df.convert_objects(convert_numeric=True)
        Out[27]:
             a
        0  0.1
        1  0.5
        2  NaN
        3  9.0
        In [29]:
        

        然后你可以放下它们:

        df.convert_objects(convert_numeric=True).dropna()
        Out[29]:
             a
        0  0.1
        1  0.5
        3  9.0
        

        更新

        自从版本 0.17.0 这个方法现在是 deprecated 并且你需要使用 to_numeric 不幸的是它在 Series 而不是整个 df 所以等效代码现在是:

        df.apply(lambda x: pd.to_numeric(x, errors='coerce')).dropna()
        

        【讨论】:

        • 谢谢!我的数据框有多个列。有些列需要有字符串。例如,我有一列“名称”和一列“年龄”。 “年龄”列必须是数字。我试过:df.age.convert_objects(convert_numeric=True) 并得到“系列”对象没有属性“convert_objects”。
        • 在这种情况下你需要做df[['age']].convert_objects(convert_numeric=True)
        • 哦,我明白了,所以 [['age']] 选择了 df 中的列。非常有帮助。但是,我得到一个 TypeError: convert_objects() got an unexpected keyword argument 'convert_numeric.我刚刚检查了文档,'convert_numeric = True' 是正确的论点。想法?
        • 好吧,我觉得我的熊猫已经过时了。现在更新。
        • 嗨。尝试使用它时,我得到一个“convert_objects deprecated”FutureWarning。有什么建议吗?
        【解决方案4】:

        您可以从dtype.kind 属性中找到列的数据类型。像df[col].dtype.kind 这样的东西。有关详细信息,请参阅the numpy docs。转置数据帧以从索引转到列。

        【讨论】:

          猜你喜欢
          • 2016-10-31
          • 2020-06-15
          • 1970-01-01
          • 2022-08-11
          • 2018-07-30
          • 2018-12-08
          • 2023-03-07
          • 2022-08-09
          • 1970-01-01
          相关资源
          最近更新 更多