【问题标题】:Drop rows if value in a specific column is not an integer in pandas dataframe如果特定列中的值不是熊猫数据框中的整数,则删除行
【发布时间】:2015-04-14 12:24:30
【问题描述】:

如果我有一个数据框并且想要删除其中一列中的值不是整数的任何行,我该怎么做?

如果值不在 0-2 范围内,另一种方法是删除行,但由于我不确定如何执行其中任何一个,我希望其他人可以这样做。

这是我尝试过的,但不知道为什么:

df = df[(df['entrytype'] != 0) | (df['entrytype'] !=1) | (df['entrytype'] != 2)].all(1)

【问题讨论】:

  • 好吧,由于运算符优先级,这将不起作用,因此您需要大括号,因此它应该是:df = df[(df['entrytype'] != 0) | (df['entrytype'] !=1) | (df['entrytype'] != 2)].all(1) 但是,如果列中有任何非数字行,则 dtype 将 @987654323 @你能不能只是测试一下呢
  • 是的,我确实对此进行了测试,因此由于 dtype 问题,我正在寻找替代方案。有哪些替代方案?
  • 你可以做df[~df['entrytype'].isin([0,1,2])] 如果你希望这些值只是那些值,这将过滤不是 0、1 或 2 的行
  • 另一种方式可能是:df['entrytype'].apply(lambda x: str(x).isdigit())

标签: python pandas


【解决方案1】:

我们有多种方法可以做到这一点,但我发现这种方法既简单又高效。

快速示例

#Using drop() to delete rows based on column value
df.drop(df[df['Fee'] >= 24000].index, inplace = True)

# Remove rows
df2 = df[df.Fee >= 24000]

# If you have space in column name
# Specify column name with in single quotes
df2 = df[df['column name']]

# Using loc
df2 = df.loc[df["Fee"] >= 24000 ]

# Delect rows based on multiple column value
df2 = df[ (df['Fee'] >= 22000) & (df['Discount'] == 2300)]

# Drop rows with None/NaN
df2 = df[df.Discount.notnull()]

【讨论】:

    【解决方案2】:

    str("-1").isdigit()False

    str("-1").lstrip("-").isdigit() 工作但不是很好。


    df.loc[df['Feature'].str.match('^[+-]?\d+$')]

    为你的问题反向设置

    df.loc[ ~(df['Feature'].str.match('^[+-]?\d+$')) ]

    【讨论】:

      【解决方案3】:

      我提出了两种方法:

      In [212]:
      
      df = pd.DataFrame({'entrytype':[0,1,np.NaN, 'asdas',2]})
      df
      Out[212]:
        entrytype
      0         0
      1         1
      2       NaN
      3     asdas
      4         2
      

      如果值的范围如您所说的那样有限,那么使用isin 将是最快的方法:

      In [216]:
      
      df[df['entrytype'].isin([0,1,2])]
      Out[216]:
        entrytype
      0         0
      1         1
      4         2
      

      否则我们可以转换为 str 然后调用.isdigit()

      In [215]:
      
      df[df['entrytype'].apply(lambda x: str(x).isdigit())]
      Out[215]:
        entrytype
      0         0
      1         1
      4         2
      

      【讨论】:

      • 嗨,这两种方法都很好,但不幸的是,只有第二种较慢的方法对我有用。一定是因为从csv导入时值被指定为字符串
      • 如果从 csv 加载,如果您没有指定 dtype 或尝试强制 dtype 则它会尝试猜测,如果您有非数字值,那么它可能会将它们更改为 str 类型,什么是你的行中的错误值吗?执行df.convert_objects(convert_numeric=True) 然后调用df.dropna() 可能会更快
      • 好的,我这样做了,它也有效:df2 = df[df['entrytype'].isin(['0','1','2'])] 但你的方式更干净我认为
      • 理想情况下,dtypes 应该设置为正确的类型,如果可能,我会尝试更改为 int,但是如果您缺少值,则无法这样做,因为 NaN 不能由 int 表示但可以用浮点数表示
      猜你喜欢
      • 2021-04-01
      • 1970-01-01
      • 2020-01-04
      • 1970-01-01
      • 2022-11-27
      • 2018-12-20
      • 1970-01-01
      • 2017-01-15
      • 2017-09-27
      相关资源
      最近更新 更多