简体   繁体   English

关于列表理解的多个条件语句

[英]Multiple conditional statements on list comprehension

So this is my code and I want to know if I can use list comprehension to execute the same operation (count the clusters within rows and output a list of length df.shape[0] ).所以这是我的代码,我想知道我是否可以使用列表理解来执行相同的操作(计算内的集群和 output 长度为df.shape[0]的列表)。 There are at least two rows for the same cluster number, but it can be more and they cycles.相同的簇号至少有两行,但可以更多,并且它们循环。 I tried but couldn't figure it out.我试过但无法弄清楚。 Any suggestions?有什么建议么?

My code:我的代码:

    import pandas as pd

    cluster_global = 0
    cluster_relativo = 0
    cluster_index = []
    for index, row in df.iterrows():
        if row['cluster'] == cluster_relativo:
            cluster_index.append(cluster_global)
        elif row['cluster'] == (cluster_relativo + 1):
            cluster_global += 1
            cluster_relativo += 1
            cluster_index.append(cluster_global)
        elif row['cluster'] == 0:
            cluster_global += 1
            cluster_relativo = 0
            cluster_index.append(cluster_global)

The DataFrame looks like DataFrame 看起来像

index指数 cluster
0 0 0 0
1 1 0 0
2 2 1 1
3 3 1 1
4 4 1 1
5 5 2 2
6 6 2 2
7 7 0 0
8 8 0 0
... ... ... ...
n n m<40米<40

Do you want this?你想要这个吗?

from itertools import groupby

result = [0 if index == 0 and key == 0
          else index
          for index, (key, group) in enumerate(groupby(my_values))
          for _ in group
          ]

print(result)

Replace my_values in the list comprehension via - df['cluster'].values.通过 - df['cluster'].values 替换列表理解中的 my_values。 to test去测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM