python - 列表理解的多个条件语句

标签 python pandas list list-comprehension

这是我的代码,我想知道是否可以使用列表理解来执行相同的操作(计算 中的簇并输出长度为 df.shape[0] 的列表)。相同的簇号至少有两行,但可以更多,并且它们循环。我尝试过但无法弄清楚。 有什么建议吗?

我的代码:

    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)

数据框看起来像

<表类=“s-表”> <标题> 索引 集群 <正文> 0 0 1 0 2 1 3 1 4 1 5 2 6 2 7 0 8 0 ... ... n 米<40

最佳答案

你想要这个吗?

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)

通过 - df['cluster'].values 替换列表理解中的 my_values。测试

关于python - 列表理解的多个条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67300601/

相关文章:

python - 使用 Pandas 在 Python 中通过查找连接 2 df

python - 有没有更好更易读的方法来合并 Pandas 中的列

c++ - 当排序标准需要额外的变量时,如何对列表进行排序? C++

python - 出于教育目的将 vb.net 代码转换为 python。未发生数值输出

python - 返回 DataFrame [Pandas] 中数据组的位置(行和列)

python - 以奇怪的方式对 Pandas 数据框进行排序和分组

list - 如何展平斯卡拉的 future list

python - 计算高效的日期加法 (Python)

python - Pandas - 创建行以在列中输入

python - 使 'isinstance' 与装饰器一起工作