python - 如何删除 Pandas 数据框中带有 NaN 的行?

标签 python python-3.x pandas

我有这个 pandas 数据框,它实际上是一个 excel 电子表格:

    Unnamed: 0  Date    Num     Company     Link    ID
0   NaN     1990-11-15  131231  apple...    http://www.example.com/201611141492/xellia...   290834
1   NaN     1990-10-22  1231    microsoft http://www.example.com/news/arnsno...     NaN
2   NaN     2011-10-20  123     apple   http://www.example.com/ator...  209384
3   NaN     2013-10-27  123     apple...    http://example.com/sections/th-shots/2016/...   098
4   NaN     1990-10-26  123     google  http://www.example.net/business/Drugmak...  098098
5   NaN     1990-10-18  1231    google...   http://example.com/news/va-rece...  NaN
6   NaN     2011-04-26  546     amazon...   http://www.example.com/news/home/20160425...    9809

我想删除 ID 列中所有具有 NaN 的行,并重新索引“索引虚列”:

    Unnamed: 0  Date    Num     Company     Link    ID
0   NaN     1990-11-15  131231  apple...    http://www.example.com/201611141492/xellia...   290834
1   NaN     2011-10-20  123     apple   http://www.example.com/ator...  209384
2   NaN     2013-10-27  123     apple...    http://example.com/sections/th-shots/2016/...   098
3   NaN     1990-10-26  123     google  http://www.example.net/business/Drugmak...  098098
4   NaN     2011-04-26  546     amazon...   http://www.example.com/news/home/20160425...    9809

我知道这可以按如下方式完成:

df = df['ID'].dropna()

或者

df[df.ID != np.nan]

或者

df = df[np.isfinite(df['ID'])]

TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

或者

df[df.ID()]

或者:

df[df.ID != '']

然后:

df.reset_index(drop=True, inplace=True)

但是,它并没有删除 ID 中的 NaN。我正在获取以前的数据框。

更新

在:

df['ID'].values

输出:

array([ '....A lot of text....',
       nan,
       "A lot of text...",
       "More text",
       'text from the site',
       nan,
       "text from the site"], dtype=object)

最佳答案

试试 df.dropna(axis = 1)

或者,df.dropna(axis = 0, subset = "ID")看看是否有帮助。

关于python - 如何删除 Pandas 数据框中带有 NaN 的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40872090/

相关文章:

python - 分组和平均 NumPy 矩阵

python - 在 Snakemake 脚本中使用 argparse

python - python 3中的operator.setitem问题

python - 如何使用 Pandas 在 x 轴上绘制列并使用索引作为 y 轴?

Python:json_normalize 一个 pandas 系列给出了 TypeError

python - Django - 获取 pre_save 信号中的 auto_now 字段

python - Django url正则表达式参数捕获

python - 为属性提供自定义 __str__ 表示

python - 在 numpy/pandas 中屏蔽包含 nan 的事件之间的间隔的优雅方法

python - 使用带有日志装饰器的 functools.wraps