【问题标题】:Python - Pandas Drop Rows with stringsPython - 带有字符串的 Pandas Drop Rows
【发布时间】:2018-03-10 00:04:40
【问题描述】:

在我的数据集中,我有几行包含字符。 我只需要包含所有整数的行。最好的方法是什么?下面的数据集: 例如,我想删除第 2 行和第 3 行,因为它们分别包含 051A、04A 和 08B。

1   2017    0   321     3   20  42  18
2   051A    0   321     3   5   69  04A
3   460     0   1633    16  38  17  08B
4   1811    0   822     8   13  65  18

【问题讨论】:

  • 您是否需要检查整数与浮点数[和其他非字符串类型]?
  • 不,我只是在寻找整数。谢谢!

标签: python python-3.x pandas


【解决方案1】:

不确定是否可以在这里避免申请

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

    0   1   2   3   4   5   6   7
0   1   2017.0  0   321 3   20  42  18.0
3   4   1811.0  0   822 8   13  65  18.0

【讨论】:

  • 一个避免apply的选项,虽然我不如pd.to_numeric(df.stack(), 'coerce').unstack().dropna()(-:也就是说,这不解决浮点数。OP说所有整数的行。如果浮点数恰好是连续,这不会放弃它。
【解决方案2】:

对于这项任务,如前所述,try / except 是一个可以处理所有情况的解决方案。

pd.DataFrame.applymap 对数据框中的每个元素应用一个函数。

def CheckInt(s):
    try: 
        int(s)
        return True
    except ValueError:
        return False

res = df[df.applymap(CheckInt).all(axis=1)].astype(int)

#    0     1  2    3  4   5   6   7
# 0  1  2017  0  321  3  20  42  18
# 3  4  1811  0  822  8  13  65  18

【讨论】:

  • 我非常喜欢这个答案! df[df.applymap(lambda x: str(x).isdigit()).all(1)].astype(int)
  • '1.1'.isdigit() 为我解析为 False。另外,当我说我喜欢“这个”答案时。我的意思是你的(-:
  • 添加了答案。
【解决方案3】:

这与@jpp 的解决方案非常相似,但检查数字的技术不同。

df[df.applymap(lambda x: str(x).isdecimal()).all(1)].astype(int)

   0     1  2    3  4   5   6   7
0  1  2017  0  321  3  20  42  18
3  4  1811  0  822  8  13  65  18

感谢@jpp 建议isdecimal 而不是isdigit

【讨论】:

  • 既然你提到了十进制,这给了我一个想法……但不知道它有多快。
【解决方案4】:

作为其他好的答案的替代方案,此解决方案使用 stack + unstack 范例来避免循环解决方案。

v = df.stack().astype(str)
v.where(v.str.isdecimal()).unstack().dropna().astype(int)

   0     1  2    3  4   5   6   7
0  1  2017  0  321  3  20  42  18
3  4  1811  0  822  8  13  65  18

【讨论】:

  • 这确实很有趣,尽管 isdecimal 的问题是它不能处理浮点数。 +1 :)
【解决方案5】:

在一行中,我认为您可以使用 pandas 的 convert_objects 函数。有了这个,我们将对象转换为整数,这将导致 NA。我们终于放弃了。

df = df.convert_objects(convert_numeric=True).dropna()

您可以在pandas documentation 上查看更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 2018-05-05
    • 2016-06-23
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    相关资源
    最近更新 更多