我是Dask新手,来自Apache Spark平台。我试图在Dask中复制一个例程,我在白天加载JSON文件,并选择一些要包含在下游计算中的字段。我发现for循环没有展开,因此只有最后一个追加部分有效(在我的例子中,这是文件数据的最后一天)。我相信,在追加操作期间,我需要某种形式的复制操作符来生成该数据框的副本,但我无法从文档中找到任何信息。我目前的解决办法是计算一个pandas数据框架并附加它,这是可以的,但我想知道是否有更好的方法。
import dask
import json
import os
os.makedirs('demodata', exist_ok=True) # Create data/ directory
b = dask.datasets.make_people() # Make records of people
b.map(json.dumps).to_textfiles('demodata/*.json') # Encode as JSON, write to disk
dict_filter = lambda x, y: dict([ (i,x[i]) for i in x if i in set(y) ])
bags = []
for in_path in glob.glob('demodata/*.json'):
in_path = Path(in_path)
file_str = in_path.stem
print('Loading file %s' % file_str)
json_bag = db.read_text(in_path).map(json.loads)
filtered_bag = json_bag.map(lambda evt: dict_filter(evt, ['age','name']))
file_dict ={'filename':file_str}
file_bag = filtered_bag.map(lambda d: {**d,**file_dict} )
bags.append(file_bag)
all_bags = db.concat(bags)
all_people = all_bags.to_dataframe().compute()
assert all_people.filename.nunique() == 10
我认为我们可以通过使用dask.bag.read_text(..., include_path=True)
关键字参数来解决这个问题,而无需循环。
import dask.bag as db
import json
import os
# Ran this once, then no more
# import dask
# os.makedirs("demodata", exist_ok=True) # Create data/ directory
# b = dask.datasets.make_people() # Make records of people
# b.map(json.dumps).to_textfiles("demodata/*.json") # Encode as JSON, write to disk
get_keys = lambda d, keys: {key: d[key] for key in d if key in keys}
df = (
db.read_text("demodata/*.json", include_path=True)
.map(lambda x: {**json.loads(x[0]), **dict(filename=os.path.basename(x[1]))})
.map(lambda evt: get_keys(evt, ["age", "name", "filename"]))
.to_dataframe()
.compute()
)
print(df)
assert df.filename.nunique() == 10
打印出
age name filename
0 50 [Chieko, Daniels] 0.json
1 52 [Irina, Tyson] 0.json
2 63 [Ali, O'connor] 0.json
3 47 [Doretta, Wiggins] 0.json
4 22 [Gregorio, Barnes] 0.json
.. ... ... ...
995 49 [Lory, Combs] 9.json
996 43 [Nicky, Mullen] 9.json
997 57 [Carolyne, Mendoza] 9.json
998 58 [Arthur, Monroe] 9.json
999 40 [Shin, Nunez] 9.json
这回答你的问题了吗?或者你在寻找一些稍微不同的东西?