根据列列表值过滤熊猫数据框

时间:2020-04-25 00:11:33

标签: python arrays pandas dataframe

我的数据框有很多列。这些列之一是数组

df
Out[191]: 
       10012005  10029008  10197000  ...  filename_int  filename      result
0           0.0       0.0       0.0  ...             1       1.0  [280, NON]
1           0.0       0.0       0.0  ...            10      10.0  [286, NON]
2           0.0       0.0       0.0  ...           100     100.0  [NON, 285]
3           0.0       0.0       0.0  ...         10000   10000.0  [NON, 286]
4           0.0       0.0       0.0  ...         10001   10001.0       [NON]
        ...       ...       ...  ...           ...       ...         ...
52708       0.0       0.0       0.0  ...          9995    9995.0       [NON]
52709       0.0       0.0       0.0  ...          9996    9996.0       [NON]
52710       0.0       0.0       0.0  ...          9997    9997.0  [285, NON]
52711       0.0       0.0       0.0  ...          9998    9998.0       [NON]
52712       0.0       0.0       0.0  ...          9999    9999.0       [NON]

[52713 rows x 4289 columns]

列结果是这些值的数组

[NON]
[123,NON]
[357,938,837]
[455,NON,288]
[388,929,NON,020]

我希望我的过滤器数据框仅显示具有非NON值的记录

因此,例如

[NON,NON]
[NON]
[]

这些将被排除

仅在文件管理器值中

[123,NON]
[357,938,837]
[455,NON,288]
[388,929,NON,020]

我尝试了此代码

df[len(df["result"])!="NON"]

但是我得到这个错误!

  File "pandas\_libs\hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: True

如何过滤我的数据框?

3 个答案:

答案 0 :(得分:2)

在此处尝试maplambda

df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [[280, 'NON'], ['NON'], [], [285]] })
df

   A           B
0  1  [280, NON]
1  2       [NON]
2  3          []
3  4       [285]

df[df['B'].map(lambda x: any(y != 'NON' for y in x))]

   A           B
0  1  [280, NON]
3  4       [285]

如果列表中至少有1个项目为“ NON”,则map中的生成器表达式将返回True。

答案 1 :(得分:1)

您可以使用apply来确定符合条件的行。在这里,该过滤器起作用了,因为apply返回了boolean

import pandas as pd
import numpy as np

vals = [280, 285, 286, 'NON', 'NON', 'NON']
listcol = [np.random.choice(vals, 3) for _ in range(100)] 
df = pd.DataFrame({'vals': listcol})

def is_non(l):
    return len([i for i in l if i != 'NON']) > 0

df.loc[df.vals.apply(is_non), :]

答案 2 :(得分:1)

我会做

[]