【发布时间】:2019-12-17 13:08:59
【问题描述】:
我在这里用虚拟数据模拟我真正想做的事情。我需要执行的步骤:
- 分别对每一列进行一些转换。
- 执行 groupby 操作以针对目标列聚合每列的一些指标。
我模拟的代码。
import dask.dataframe as dd
from dask.distributed import Client, as_completed, LocalCluster
cluster = LocalCluster(processes=False)
client = Client(cluster, asynchronous=True)
csv_loc = '/Users/apple/Downloads/iris.data'
df = dd.read_csv(csv_loc) # ofcourse, u need to give aws creds here. Omitting it. Assuming u can read from s3 or otherwise.
client.persist(df)
cols = ['sepal_length', 'sepal_width' ,'petal_length' ,'petal_width', 'species']
# This is needed because I am doing some custom operation on actual data
for c in cols:
if c != 'species':
df[c] = df[c].map(lambda x: x*10)
client.persist(df) # Is this the trouble?
def agg_bivars(col_name):
agg_df = df.groupby('species')[col_name].sum().compute()
return {col_name : agg_df}
agg_futures = client.map(agg_bivars, ['sepal_length', 'sepal_width' ,'petal_length' ,'petal_width'])
for batch in as_completed(agg_futures, with_results=True).batches():
for future, result in batch:
print('result: {}'.format(result))
client.restart()
client.close()
cluster.close()
您可以从此link 下载数据。这是一个非常标准的在线流行数据。
我得到的结果:不同列的分组结果相同。
预期结果:不同列需要不同的 groupby 结果。
结果:
result: {'sepal_width': species
Iris-setosa 2503.0
Iris-versicolor 2968.0
Iris-virginica 3294.0
Name: sepal_length, dtype: float64}
result: {'sepal_length': species
Iris-setosa 2503.0
Iris-versicolor 2968.0
Iris-virginica 3294.0
Name: sepal_length, dtype: float64}
result: {'petal_width': species
Iris-setosa 2503.0
Iris-versicolor 2968.0
Iris-virginica 3294.0
Name: sepal_length, dtype: float64}
result: {'petal_length': species
Iris-setosa 2503.0
Iris-versicolor 2968.0
Iris-virginica 3294.0
Name: sepal_length, dtype: float64}
Process finished with exit code 0
如果我只在 df 上进行 groupby,它可以正常工作。但是,这里的问题是我必须在每个列的 groupby 之前对整个 df 进行一些转换。注意我在做client.persist(df) 两次。我做了第二次,因为无论我做了什么新的转换,我都希望它们能够持续存在,以便我可以快速查询。
【问题讨论】:
-
第二个
client.persist是不必要的,第一个应该被称为df = client.persist(df)
标签: python pandas dask dask-distributed