如何在For 1 to n循环中创建n个数据帧?

时间:2020-09-12 18:57:16

标签: python for-loop iteration

这是我想要做的。我有一个名为df_prod_pivot_cluster的数据框,其中一列名为'cluster',其取值范围为1到25。 我想创建25个数据框。我在下面编写了这段代码,但是如何以更优雅的方式做到这一点(例如:对于range(1,25)中的x:)?

ts_cluster1 = df_prod_pivot_cluster.loc[df_prod_pivot_cluster['cluster'] == 1]
ts_cluster1 = ts_cluster1.drop(columns='EASTING','NORTHING'])
ts_cluster1 = ts_cluster1.fillna(0)
ts_cluster1 = ts_cluster1.sum()

ts_cluster2 = df_prod_pivot_cluster.loc[df_prod_pivot_cluster['cluster'] == 2]
ts_cluster2 = ts_cluster2.drop(columns=['EASTING', 'NORTHING'])
ts_cluster2 = ts_cluster2.fillna(0)
ts_cluster2 = ts_cluster2.sum()
.
.
.

ts_cluster25 = df_prod_pivot_cluster.loc[df_prod_pivot_cluster['cluster'] == 25]
ts_cluster25 = ts_cluster25.drop(columns=['EASTING', 'NORTHING'])
ts_cluster25 = ts_cluster25.fillna(0)
ts_cluster25 = ts_cluster25.sum()

1 个答案:

答案 0 :(得分:0)

此代码对我有用:

d = {}
for i in range(1, 26):
    d["ts_cluster{}".format(i)] = df_prod_pivot_cluster.loc[df_prod_pivot_cluster['cluster'] == i]
    d["ts_cluster{}".format(i)] = pd.DataFrame(d["ts_cluster{}".format(i)].sum())