代码之家  ›  专栏  ›  技术社区  ›  Jeremy Barnes

删除包含整数字符串的数据帧行

  •  1
  • Jeremy Barnes  · 技术社区  · 10 年前

    我有一个带有列的pandas数据框架

    [Brand, CPL1, CPL4, Part Number, Calendar Year/Month, value, type]
    

    当它们从StatsModels X13中出来时,它们有时会在其上下文中没有意义的值中使用非常大的整数字符串表示,例如:

    [float(1.2), float(1.3), str("63478"), float(1.1)]
    

    如何删除发生这种情况的行?由于它们是整数的字符串表示,所以我不能将它们或任何类似的方法进行转换。

    1 回复  |  直到 10 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    你可以使用 boolean indexing 检查是否 type 是 string :

    数据帧 :

    df = pd.DataFrame([[float(1.2), float(1.3), str("63478"), float(1.1)],
                      [float(1.2), float(1.3), float(1.1), str("63478")]]).T
    
    print (df)
          0      1
    0    1.2    1.2
    1    1.3    1.3
    2  63478    1.1
    3    1.1  63478
    
    print (df.applymap(lambda x: isinstance(x, str)))
           0      1
    0  False  False
    1  False  False
    2   True  False
    3  False   True
    
    print (df.applymap(lambda x: isinstance(x, str)).any(axis=1))
    0    False
    1    False
    2     True
    3     True
    dtype: bool
    
    print (df[~df.applymap(lambda x: isinstance(x, str)).any(axis=1)])
         0    1
    0  1.2  1.2
    1  1.3  1.3
    

    :

    s = pd.Series([float(1.2), float(1.3), str("63478"), float(1.1)])
    print (s)
    0      1.2
    1      1.3
    2    63478
    3      1.1
    dtype: object
    
    print (s.apply(lambda x: isinstance(x, str)))
    0    False
    1    False
    2     True
    3    False
    dtype: bool
    
    print (s[~s.apply(lambda x: isinstance(x, str))])
    0    1.2
    1    1.3
    3    1.1
    dtype: object