【问题标题】:Python pandas Filtering out nan from a data selection of a column of stringsPython pandas从一列字符串的数据选择中过滤掉nan
【发布时间】:2014-04-28 09:16:03
【问题描述】:

如果不使用groupby,我将如何过滤掉没有NaN 的数据?

假设我有一个矩阵,客户将填写 'N/A','n/a' 或其任何变体,其他人将其留空:

import pandas as pd
import numpy as np


df = pd.DataFrame({'movie': ['thg', 'thg', 'mol', 'mol', 'lob', 'lob'],
                  'rating': [3., 4., 5., np.nan, np.nan, np.nan],
                  'name': ['John', np.nan, 'N/A', 'Graham', np.nan, np.nan]})

nbs = df['name'].str.extract('^(N/A|NA|na|n/a)')
nms=df[(df['name'] != nbs) ]

输出:

>>> nms
  movie    name  rating
0   thg    John       3
1   thg     NaN       4
3   mol  Graham     NaN
4   lob     NaN     NaN
5   lob     NaN     NaN

我将如何过滤掉 NaN 值,以便我可以得到这样的结果:

  movie    name  rating
0   thg    John       3
3   mol  Graham     NaN

我猜我需要像 ~np.isnan 这样的东西,但 tilda 不适用于字符串。

【问题讨论】:

  • df[df.name.notnull()]

标签: python pandas dataframe


【解决方案1】:

放下它们:

nms.dropna(thresh=2)

这将删除至少有两个非NaN 的所有行。

然后你可以把名字放在NaN的地方:

In [87]:

nms
Out[87]:
  movie    name  rating
0   thg    John       3
1   thg     NaN       4
3   mol  Graham     NaN
4   lob     NaN     NaN
5   lob     NaN     NaN

[5 rows x 3 columns]
In [89]:

nms = nms.dropna(thresh=2)
In [90]:

nms[nms.name.notnull()]
Out[90]:
  movie    name  rating
0   thg    John       3
3   mol  Graham     NaN

[2 rows x 3 columns]

编辑

实际上看看你最初想要什么,你可以在没有dropna调用的情况下做到这一点:

nms[nms.name.notnull()]

更新

三年后看这个问题,有一个错误,首先thresh arg 寻找至少nNaN 值所以实际上输出应该是:

In [4]:
nms.dropna(thresh=2)

Out[4]:
  movie    name  rating
0   thg    John     3.0
1   thg     NaN     4.0
3   mol  Graham     NaN

有可能是我3年前弄错了,或者我运行的pandas版本有bug,这两种情况都是完全可能的。

【讨论】:

    【解决方案2】:

    最简单的解决方案:

    filtered_df = df[df['name'].notnull()]
    

    因此,它只过滤掉 'name' 列中没有 NaN 值的行。

    对于多列:

    filtered_df = df[df[['name', 'country', 'region']].notnull().all(1)]
    

    【讨论】:

      【解决方案3】:
      df = pd.DataFrame({'movie': ['thg', 'thg', 'mol', 'mol', 'lob', 'lob'],'rating': [3., 4., 5., np.nan, np.nan, np.nan],'name': ['John','James', np.nan, np.nan, np.nan,np.nan]})
      
      for col in df.columns:
          df = df[~pd.isnull(df[col])]
      

      【讨论】:

        【解决方案4】:
        df.dropna(subset=['columnName1', 'columnName2'])
        

        【讨论】:

          【解决方案5】:

          你也可以使用query:

          out = df.query("name.notna() & name !='N/A'", engine='python')
          

          输出:

            movie  rating    name
          0   thg     3.0    John
          3   mol     NaN  Graham
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-11-17
            • 2016-02-19
            • 2020-01-16
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多