我试图重写一些csv读取代码,以便能够在Python 3.2.2中的多个核心上运行它.我尝试使用Pool多处理的对象,我从工作示例改编(并且已经为我的项目的另一部分工作).我遇到了一条错误消息,我发现很难解密和排除故障.
错误:
Traceback (most recent call last):
File "parser5_nodots_parallel.py", line 256, in <module>
MG,ppl = csv2graph(r)
File "parser5_nodots_parallel.py", line 245, in csv2graph
node_chunks)
File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/multiprocessing/pool.py", line 251, in map
return self.map_async(func, iterable, chunksize).get()
File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/multiprocessing/pool.py", line 552, in get
raise self._value
AttributeError: __exit__
Run Code Online (Sandbox Code Playgroud)
相关代码:
import csv
import time
import datetime
import re
from operator import itemgetter
from multiprocessing import Pool
import itertools
def chunks(l,n):
"""Divide a list of nodes `l` in `n` chunks"""
l_c = iter(l)
while …Run Code Online (Sandbox Code Playgroud) 我很困惑pandas如何用这些行吹出日期时间对象的界限:
import pandas as pd
BOMoffset = pd.tseries.offsets.MonthBegin()
# here some code sets the all_treatments dataframe and the newrowix, micolix, mocolix counters
all_treatments.iloc[newrowix,micolix] = BOMoffset.rollforward(all_treatments.iloc[i,micolix] + pd.tseries.offsets.DateOffset(months = x))
all_treatments.iloc[newrowix,mocolix] = BOMoffset.rollforward(all_treatments.iloc[newrowix,micolix]+ pd.tseries.offsets.DateOffset(months = 1))
Run Code Online (Sandbox Code Playgroud)
这all_treatments.iloc[i,micolix]是一个日期时间设置pd.to_datetime(all_treatments['INDATUMA'], errors='coerce',format='%Y%m%d'),并且INDATUMA是格式中的日期信息20070125.
这个逻辑似乎适用于模拟数据(没有错误,日期有意义),所以目前我无法在我的整个数据失败时重现,并出现以下错误:
pandas.tslib.OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 2262-05-01 00:00:00
Run Code Online (Sandbox Code Playgroud) 作为一个新手,我更喜欢GitHub应用程序本身的简单性来处理我们的GitHub托管的git项目.但是,为了同步/推拉另一个遥控器,我需要尝试SourceTree.(我没有足够的信心将所有内容保留在命令行中.)
我可以使用GitHub应用程序进行大部分编辑我的(主要)本地仓库并与GitHub.com同步,并且偶尔启动SourceTree同步(我的主要本地仓库,因为我无法将github.com远程直接同步到另一个远程,我可以?)与辅助遥控器?这会没有任何冲突吗?
对于那些感兴趣的人:我需要在共享位置使用辅助遥控器,因为它也与无法访问互联网的帐户共享以直接与github.com repo同步.
git github github-for-mac github-for-windows atlassian-sourcetree
我是新手scikit-learn,但它做了我所希望的.现在,令人抓狂的是,唯一剩下的问题是我找不到如何打印(或甚至更好地写入一个小文本文件)它估计的所有系数,它所选择的所有功能.这样做的方法是什么?
与SGDClassifier相同,但我认为对于所有可以适合的基础对象,交叉验证或没有交叉验证都是相同的.完整的脚本如下.
import scipy as sp
import numpy as np
import pandas as pd
import multiprocessing as mp
from sklearn import grid_search
from sklearn import cross_validation
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import SGDClassifier
def main():
print("Started.")
# n = 10**6
# notreatadapter = iopro.text_adapter('S:/data/controls/notreat.csv', parser='csv')
# X = notreatadapter[1:][0:n]
# y = notreatadapter[0][0:n]
notreatdata = pd.read_stata('S:/data/controls/notreat.dta')
notreatdata = notreatdata.iloc[:10000,:]
X = notreatdata.iloc[:,1:]
y = notreatdata.iloc[:,0]
n = y.shape[0]
print("Data lodaded.")
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, …Run Code Online (Sandbox Code Playgroud) 我想将数据写入文件,其中CSV中的行应该看起来像这个列表(直接来自Python控制台):
row = ['\xef\xbb\xbft_11651497', 'http://kozbeszerzes.ceu.hu/entity/t/11651497.xml', "Szabolcs Mag '98 Kft.", 'ny\xc3\xadregyh\xc3\xa1za', 'ny\xc3\xadregyh\xc3\xa1za', '4400', 't\xc3\xbcnde utca 20.', 47.935175, 21.744975, u'Ny\xedregyh\xe1za', u'Borb\xe1nya', u'Szabolcs-Szatm\xe1r-Bereg', u'Ny\xedregyh\xe1zai', u'20', u'T\xfcnde utca', u'Magyarorsz\xe1g', u'4405']
Run Code Online (Sandbox Code Playgroud)
Py2k不做Unicode,但我有一个UnicodeWriter包装器:
import cStringIO, codecs
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, …Run Code Online (Sandbox Code Playgroud) 我有下面的代码来解析一些 csv 数据。关键是最后几行,其余的只是为了显示上下文。基本上,我的数据最后有三列,ID 变量 LopNr 和年份“无论如何”应该有整数,但我将整个 DataFrame 转换为整数以防万一。为什么在生成的 csv 文件中,LopNr 和年份列得到“.0”,而包含聚合数据的第三列实际上被转换为整数并且输出时没有“.0”?我本以为.astype(int)所有列都会有整数,并且我们导出到 csv 而不将它们转换回浮点数。
import iopro
from pandas import *
neuro = DataFrame()
for year in xrange(2005,2012):
for month in xrange(1,13):
if year == 2005 and month < 7:
continue
filename = 'Q:\\drugs\\lmed_' + str(year) + '_mon'+ str(month) +'.txt'
adapter = iopro.text_adapter(filename,parser='csv',field_names=True,output='dataframe',delimiter='\t')
monthly = adapter[['LopNr','ATC','TKOST']][:]
monthly['year']=year
neuro = neuro.append(monthly[(monthly.ATC.str.startswith('N')) & (~(monthly.TKOST.isnull()))])
neuro = neuro.groupby(['LopNr','year']).sum()
neuro = neuro.astype(int)
neuro.to_csv('Q:\\drugs\\annual_neuro_costs.csv')
Run Code Online (Sandbox Code Playgroud) 使用 networkx 模块,我在 Python 3.2 下进行了一些网络分析,其中我需要将一个二分图(链接到其牢房的囚犯:在下面的代码中输入图 B)投影到一个子图(如果牢房中的囚犯都有同一单元中的重叠咒语:使用定义图 B 的囚犯节点的集合节点的输入,生成输出图 G)。我不需要特殊的算法来提出任何匹配或最佳匹配,我只需要收集满足某些条件的所有链接。因此我发现的其他 SO 帖子并不真正适用。但:
当我给它提供越来越多的数据时,我当前的代码正在崩溃(RAM、交换和 CPU 方面)。如果您发现使用 5 层循环简化下面代码的方法,请告诉我。我不确定是否需要任何有关 networkx 的知识,或者我的边缘属性标签的详细信息是否相关。谢谢!
def time_overlap_projected_graph_parallel(B, nodes):
G=nx.MultiGraph()
G.add_nodes_from((n,B.node[n]) for n in nodes)
for u in nodes:
unbrs = set(B[u])
nbrs2 = set((n for nbr in unbrs for n in B[nbr])) - set([u])
for v in nbrs2:
for mutual_cell in set(B[u]) & set(B[v]):
for uspell in B.get_edge_data(u,mutual_cell).values():
ustart = uspell[1]
uend = uspell[2]
for vspell in B.get_edge_data(v,mutual_cell).values():
vstart = vspell[1]
vend = vspell[2]
if uend …Run Code Online (Sandbox Code Playgroud) 我的代码运行正常较小的测试样品,如10000行的数据X_train,y_train.当我为数百万行调用它时,我得到了结果错误.是包中的错误,还是我可以做不同的事情?我正在使用Anaconda 2.0.1中的Python 2.7.7,我将来自Anaconda的多处理软件包的pool.py和来自scikit-learn的外部软件包的parallel.py放在我的Dropbox上.
测试脚本是:
import numpy as np
import sklearn
from sklearn.linear_model import SGDClassifier
from sklearn import grid_search
import multiprocessing as mp
def main():
print("Started.")
print("numpy:", np.__version__)
print("sklearn:", sklearn.__version__)
n_samples = 1000000
n_features = 1000
X_train = np.random.randn(n_samples, n_features)
y_train = np.random.randint(0, 2, size=n_samples)
print("input data size: %.3fMB" % (X_train.nbytes / 1e6))
model = SGDClassifier(penalty='elasticnet', n_iter=10, shuffle=True)
param_grid = [{
'alpha' : 10.0 ** -np.arange(1,7),
'l1_ratio': [.05, .15, .5, .7, .9, .95, …Run Code Online (Sandbox Code Playgroud) 我列出了一些网络分析的大量输出,列出了每行的边缘,这导致了几十GB,延长了我的资源限制(低估).因为我只处理数值,所以我想到我可能比使用Py3k默认值更聪明.即如果我只有数字(以及空格和偶尔的小数点),其他一些字符编码可能会为我节省相当多的空间.由于受到限制,我甚至可以保存在行结尾(不要将Windows标准CRLF复制).这方面的最佳做法是什么?
示例行将如下所示:
62233 242344 0.42442423
(实际上最后一个数字实际上是毫无意义的,我会将它切回三个非零数字.)
因为我需要在文本文件中读取其他软件(实际上是Stata),我不能将数据保存在任意二进制文件中,尽管我看不出为什么Stata只会读取UTF-8文本.或者你只是说避免使用UTF-8几乎不能为我节省任何费用?
我认为压缩对我来说不起作用,因为我逐行写文本,即使在此期间限制输出大小也是很好的.我可能很容易弄错压缩是如何工作的,但我认为它可以在文件生成后节省空间,但我的问题是我的代码崩溃已经因为我正在制作文本文件(逐行).
感谢所有想法和澄清问题!
对于writerow的csv.DictWriter,我需要填写字典(的一部分)是空的.我发现没有立即解决方案.有吗?
喜欢
fieldnames = ['first','last']
Run Code Online (Sandbox Code Playgroud)
伪代码
row = fieldnames.fill(None)
Run Code Online (Sandbox Code Playgroud)
结果
print(row)
['first':None,'last':None]
Run Code Online (Sandbox Code Playgroud)
以便
destination.writerow(row)
Run Code Online (Sandbox Code Playgroud)
结果是
,
Run Code Online (Sandbox Code Playgroud) python ×10
python-3.x ×4
scikit-learn ×3
anaconda ×2
csv ×2
pandas ×2
performance ×2
datetime ×1
dictionary ×1
git ×1
github ×1
io ×1
loops ×1
networkx ×1
numpy ×1
pool ×1
python-2.7 ×1
types ×1
unicode ×1