Python 根据值插入特定于列的NaN并删除行

Python 根据值插入特定于列的NaN并删除行,python,pandas,dataframe,insert,nan,Python,Pandas,Dataframe,Insert,Nan,我对昆虫进行了几次假设性试验。我想用低<强>RESULT1的值“不小于10” >行,但我想留下一个值为“强>单行< /强>的NaN,以显示执行了哪一个测试和哪一个虫。< /P> from pandas import Series, DataFrame import numpy as np A = Series(['A','A','B','B','B','C']) B = Series(['ant','flea','flea','spider','spider','flea']) C = Ser

我对昆虫进行了几次假设性试验。我想用低<强>RESULT1的值“不小于10”<强> >行,但我想留下一个值为“强>单行< /强>的NaN,以显示执行了哪一个测试和哪一个虫。< /P>
from pandas import Series, DataFrame
import numpy as np

A = Series(['A','A','B','B','B','C'])
B = Series(['ant','flea','flea','spider','spider','flea'])
C = Series([88,77,1,3,2,67])
D = Series(np.random.randn(6))

df = DataFrame({'test':A.values,'insect':B.values,
            'result_1':C.values,'result_2':D.values},
           columns=['test','insect','result_1','result_2'])
df
因此,原始数据帧如下所示:

由于指数2、3和4具有结果_1值,我认为您可以使用:

#add NaN by condition
df.loc[df.result_1 < 10, ['result_1','result_2']] = np.nan 
#drop duplicated by column insect
df[df.result_1.isnull()] = df[df.result_1.isnull()].drop_duplicates(subset='insect')
df = df.dropna(how='all')
print (df)
  test  insect  result_1  result_2
0    A     ant      88.0 -0.037844
1    A    flea      77.0 -1.088879
2    B    flea       NaN       NaN
3    B  spider       NaN       NaN
5    C    flea      67.0  1.455632
mask = df.result_1 < 10

df.loc[mask, ['result_1','result_2']] = np.nan 
a = df[mask].duplicated(subset='insect')
print (a)
2    False
3    False
4     True
dtype: bool

a = a[a].index
df = df.drop(a)
print (df)
  test  insect  result_1  result_2
0    A     ant      88.0 -0.176274
1    A    flea      77.0 -0.123691
2    B    flea       NaN       NaN
3    B  spider       NaN       NaN
5    C    flea      67.0 -0.310655