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

2024-09-19 20:51:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我对昆虫进行了几次假设性试验。我想删除结果1值“小于10”的行,我认为这不重要,但想在值a单行中留下一个NaN,以显示执行了哪个测试以及对哪个昆虫执行了测试。你知道吗

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

原来的数据帧是这样的:

enter image description here

因为索引2、3和4有结果\u1值<;10,我想删除所有这些行,但要注意的是,只剩下一行(在两个结果列中都有NaN),以表明测试B是在跳蚤上执行的(index2),应该留下一行来显示测试B确实是在spider上执行的(在索引3和4中,一个需要删除,另一个需要在results列中插入NaN)。你知道吗

因此,生成的数据帧应该如下所示:

enter image description here


Tags: 数据testimportdataframedfnpresultnan
1条回答
网友
1楼 · 发布于 2024-09-19 20:51:55

我想你可以用:

#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

另一个解决方案是找到相关索引,然后用index^{}

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

相关问题 更多 >