首页 > 解决方案 > 根据列列表值过滤熊猫数据框

问题描述

我的数据框有很多列。其中一列是数组

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

如何过滤我的数据框?

标签: pythonarrayspandasdataframe

解决方案


map在这里尝试lambda

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]

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


推荐阅读