【问题标题】:How to drop rows not containing string type in a column in Pandas?如何在 Pandas 的列中删除不包含字符串类型的行?
【发布时间】:2016-10-31 16:19:32
【问题描述】:

我有一个包含四列的 csv 文件。我是这样读的:

df = pd.read_csv('my.csv', error_bad_lines=False, sep='\t', header=None, names=['A', 'B', 'C', 'D'])

现在,C 字段包含字符串值。但在某些行中有非字符串类型(浮点数或数字)值。如何删除这些行?我使用的是 Pandas 0.18.1 版。

【问题讨论】:

    标签: python string python-2.7 pandas dataframe


    【解决方案1】:

    您可以将boolean indexingto_numeric 创建的mask 和参数errors='coerce' 一起使用-您会得到NaN,其中是字符串值。然后查看isnull

    df = pd.DataFrame({'A':[1,2,3],
                       'B':[4,5,6],
                       'C':['a',8,9],
                       'D':[1,3,5]})
    print (df)
       A  B  C  D
    0  1  4  a  1
    1  2  5  8  3
    2  3  6  9  5
    
    print (pd.to_numeric(df.C, errors='coerce'))
    0    NaN
    1    8.0
    2    9.0
    Name: C, dtype: float64
    
    print (pd.to_numeric(df.C, errors='coerce').isnull())
    0     True
    1    False
    2    False
    Name: C, dtype: bool
    
    print (df[pd.to_numeric(df.C, errors='coerce').isnull()])
       A  B  C  D
    0  1  4  a  1
    

    【讨论】:

    • 这种方法对于 500,000 行的数据框是否有效?
    【解决方案2】:

    设置

    df = pd.DataFrame([['a', 'b', 'c', 'd'], ['e', 'f', 1.2, 'g']], columns=list('ABCD'))
    print df
    
       A  B    C  D
    0  a  b    c  d
    1  e  f  1.2  g
    

    请注意,您可以查看各个单元格类型。

    print type(df.loc[0, 'C']), type(df.loc[1, 'C'])
    
    <type 'str'> <type 'float'>
    

    蒙版和切片

    print df.loc[df.C.apply(type) != float]
    
       A  B  C  D
    0  a  b  c  d
    

    更通用

    print df.loc[df.C.apply(lambda x: not isinstance(x, (float, int)))]
    
       A  B  C  D
    0  a  b  c  d
    

    您也可以使用float 来尝试确定它是否可以是浮点数。

    def try_float(x):
        try:
            float(x)
            return True
        except:
            return False
    
    print df.loc[~df.C.apply(try_float)]
    
       A  B  C  D
    0  a  b  c  d
    

    这种方法的问题是您将排除可以解释为浮点数的字符串。

    比较我提供的几个选项的时间以及 jezrael 的解决方案与小数据帧。

    对于具有 500,000 行的数据框:

    检查它的类型是否为浮点数似乎是最好的,它后面是数字。如果您需要检查 int 和 float,我会选择 jezrael 的答案。如果您可以避免检查浮动,请使用那个。

    【讨论】:

    • 有理由匹配“not float or int”而不是“is str”吗? df.loc[df.C.apply(lambda x: isinstance(x, str))]
    【解决方案3】:

    使用 pandas.DataFrame.select_dtypes 方法。 前任。

    df.select_dtypes(exclude='object')
             or
    df.select_dtypes(include=['int64','float','int'])
    

    【讨论】:

      猜你喜欢
      • 2022-08-11
      • 2015-01-02
      • 1970-01-01
      • 2020-09-11
      • 2017-03-18
      • 2019-12-02
      • 1970-01-01
      • 2022-11-07
      • 1970-01-01
      相关资源
      最近更新 更多