我有一个看起来像这样的数据框:
ID AgeGroups PaperIDs
0 1 [3, 3, 10] [A, B, C]
1 2 [5] [D]
2 3 [4, 12] [A, D]
3 4 [2, 6, 13, 12] [X, Z, T, D]
我想提取列中的列表的AgeGroups
至少2个值小于7且至少1个值大于8的行。
因此结果应如下所示:
ID AgeGroups PaperIDs
0 1 [3, 3, 10] [A, B, C]
3 4 [2, 6, 13, 12] [X, Z, T, D]
我不确定该怎么做。
首先创建一个帮手DataFrame
,并通过比较DataFrame.lt
和DataFrame.gt
,然后通过系列Series.ge
通过和连锁口罩&
的按位与:
import ast
#if not lists
#df['AgeGroups'] = df['AgeGroups'].apply(ast.literal_eval)
df1 = pd.DataFrame(df['AgeGroups'].tolist())
df = df[df1.lt(7).sum(axis=1).ge(2) & df1.gt(8).sum(axis=1).ge(1)]
print (df)
ID AgeGroups PaperIDs
0 1 [3, 3, 10] [A, B, C]
3 4 [2, 6, 13, 12] [X, Z, T, D]
或list comprehension
与compare numpy数组一起使用,按计数sum
并比较链接的两个计数and
,因为标量为:
m = [(np.array(x) < 7).sum() >= 2 and (np.array(x) > 8).sum() >=1 for x in df['AgeGroups']]
df = df[m]
print (df)
ID AgeGroups PaperIDs
0 1 [3, 3, 10] [A, B, C]
3 4 [2, 6, 13, 12] [X, Z, T, D]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句