Yas*_*eem 4 python multithreading dataframe pandas
有人可以告诉我一种在多个线程将要使用必须将数据附加到数据帧中的函数的情况下以python方式将数据添加到pandas数据帧中的方法吗?
我的代码从URL抓取数据,然后我使用df.loc [index] ...将被抓取的行添加到数据框中。
自从我启动了一个多线程之后,该线程基本上将每个URL分配给每个线程。简而言之,一次刮掉了许多页面...
如何将这些行附加到数据框中?
不建议将行一一添加到数据框。我建议您在列表中构建数据,然后在末尾合并这些列表,然后在整个数据集的末尾仅调用DataFrame构造函数一次。
例:
# help from http://stackoverflow.com/a/28463266/3393459
# and http://stackoverflow.com/a/2846697/3393459
from multiprocessing.dummy import Pool as ThreadPool
import requests
import pandas as pd
pool = ThreadPool(4)
# called by each thread
def get_web_data(url):
return {'col1': 'something', 'request_data': requests.get(url).text}
urls = ["http://google.com", "http://yahoo.com"]
results = pool.map(get_web_data, urls)
print results
print pd.DataFrame(results)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4813 次 |
| 最近记录: |