使用组,仅删除重复的NaN

时间:2016-06-26 17:08:42

标签: python pandas

我的数据按照Assay,Image和Roi进行分组,对于每个组,我希望删除除强度'中强度为NaN值的第一行以外的所有行。柱。

我的尝试可以删除重复项,但这并不是特定于NaN值。

from pandas import Series, DataFrame
import pandas as pd
import numpy as np

df = DataFrame({'assay':['cnt']*11,
                'image':['001']*10+['002'],
                'roi':['1']*5+['2']*5+['3'],
                'dist':[99,90,50,2,30,65,95,30,56,5,33],
                'cellArea':[99,90,50,2,30,65,95,30,56,5,33],
                'xy':np.fabs(np.random.randn(11)*100),
                'intensity':[88,88,1,3,67,67,67,95,1,3,2]},
               columns=['assay','image','roi','dist','xy','cellArea','intensity','adjacency'])
df.loc[df.intensity < 10, ['intensity','xy']] = np.nan
df

enter image description here

df.groupby(['assay','image','roi']).apply(lambda x: x.drop_duplicates(['intensity'], keep='first'))

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以将drop_duplicates检查程序传递给lambda函数,而不是使用duplicated & is.null

df.groupby(['assay','image','roi']).apply(lambda x: x.loc[~(x.duplicated(['intensity']) & x.intensity.isnull())])