【发布时间】:2021-07-21 19:57:53
【问题描述】:
这是我的代码,我想知道我是否可以使用列表推导来执行相同的操作(计算 rows 中的集群并输出长度为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)
DataFrame 看起来像
| index | cluster |
|---|---|
| 0 | 0 |
| 1 | 0 |
| 2 | 1 |
| 3 | 1 |
| 4 | 1 |
| 5 | 2 |
| 6 | 2 |
| 7 | 0 |
| 8 | 0 |
| ... | ... |
| n | m<40 |
【问题讨论】:
-
您能否解释一下为什么您想要将这么多不同的东西表达为一个单一的理解?此外,
df的一个小型( -
为了在计算集群数量的同时进行更快的计算,我所读到的所有内容都指出列表理解比 iterrows 更好。抱歉,如果这是不切实际的,这是我在这里的第一篇文章,但这里是:my_index = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 , 15, 16, 17, 18, 19] my_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0, 0, 0, 0, 1, 1]
标签: python pandas list list-comprehension