查找嵌套子列表中的值是否大于列中的X

2024-10-01 07:43:14 发布

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

数据帧:

col1
[[0.43], [0.46], [1.0], [0.323]]
[[0.33], [0.66], [1.0], [0.3412]]
[[0.27], [0.42], [0.13], [0.332]]

我试图根据以下内容创建一列:col11>;=的嵌套列表中是否有数字。5然后是“是”,否则是“否”

结果:

col1                                col2
[[0.43], [0.46], [1.0], [0.323]]    yes
[[0.33], [0.66], [1.0], [0.3412]]   yes
[[0.27], [0.42], [0.13], [0.332]]   no 

最好有一个列,列中的数字在嵌套列表中的位置为>;=。5.对于上述df,这将是col3: 3,3,N/A

这样想:

for i in df.col1:
    print(i)
    if j in i >= .05:
        print(i,"yes")
    else:
        print(i,"no")

Tags: 数据noingtdf列表forif
3条回答

你能行

sub_df = df[pd.DataFrame(df['col1'].apply(lambda x : sum(x,[])).tolist()).ge(0.5).any(1).values]

将列表理解与any一起使用any比{}快,因为它在{}上短路

df['col2'] =  [any(y[0] >= 0.5 for y in x) for x in df.col1]

Out[1815]:
                                col1   col2
0   [[0.43], [0.46], [1.0], [0.323]]   True
1  [[0.33], [0.66], [1.0], [0.3412]]   True
2  [[0.27], [0.42], [0.13], [0.332]]  False

一些时间安排

df = pd.concat([df]*10000, ignore_index=True)

In [1820]: %timeit  [any(y[0] >= 0.5 for y in x) for x in df.col1]
41.2 ms ± 1.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [1823]: %timeit df['col1'].apply(lambda x: max(e[0] for e in x) >= 0.5)
51.9 ms ± 1.58 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

max理解旁侧测试列表

In [1827]: %timeit [max(y[0] for y in x) >= 0.5 for x in df.col1]
49.9 ms ± 2.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

因此,any虽然不显著,但速度更快

一个简单的apply就可以了

df['col2'] = df['col1'].apply(lambda x: max(e[0] for e in x) > 0.5)

输出

                                col1   col2
0   [[0.43], [0.46], [1.0], [0.323]]   True
1  [[0.33], [0.66], [1.0], [0.3412]]   True
2  [[0.27], [0.42], [0.13], [0.332]]  False

相关问题 更多 >