我有一个模糊的字符串匹配脚本,在400万公司名称的大海捞针中寻找大约30K针.虽然脚本工作正常,但我在AWS h1.xlarge上通过并行处理加速处理的尝试失败了,因为我的内存不足.
我不想试图获得更多内存,而是根据我之前的问题解释,我想找出如何优化工作流程 - 我对此很新,所以应该有足够的空间.顺便说一句,我已经尝试过排队(虽然工作但是遇到了同样的问题MemoryError,再看看一堆非常有用的SO贡献,但还没有完成.)
这是与代码最相关的内容.我希望它足以澄清逻辑 - 很高兴根据需要提供更多信息:
def getHayStack():
## loads a few million company names into id: name dict
return hayCompanies
def getNeedles(*args):
## loads subset of 30K companies into id: name dict (for allocation to workers)
return needleCompanies
def findNeedle(needle, haystack):
""" Identify best match and return results with score """
results = {}
for hayID, hayCompany in haystack.iteritems():
if not isnull(haystack[hayID]):
results[hayID] = levi.setratio(needle.split(' '),
hayCompany.split(' '))
scores = list(results.values()) …Run Code Online (Sandbox Code Playgroud) python performance memory-management multiprocessing string-matching
我有两个DataFrames:
import pandas as pd
import io
from scipy import stats
ctrl=u"""probegenes,sample1,sample2,sample3
1415777_at Pnliprp1,20,0.00,11
1415884_at Cela3b,47,0.00,100
1415805_at Clps,17,0.00,55
1115805_at Ckkk,77,10.00,5.5
"""
df_ctrl = pd.read_csv(io.StringIO(ctrl),index_col='probegenes')
test=u"""probegenes,sample1,sample2,sample3
1415777_at Pnliprp1,20.1,10.00,22.3
1415805_at Clps,7,3.00,1.5
1415884_at Cela3b,47,2.01,30"""
df_test = pd.read_csv(io.StringIO(test),index_col='probegenes')
Run Code Online (Sandbox Code Playgroud)
它们看起来像这样:
In [35]: df_ctrl
Out[35]:
sample1 sample2 sample3
probegenes
1415777_at Pnliprp1 20 0 11.0
1415884_at Cela3b 47 0 100.0
1415805_at Clps 17 0 55.0
1115805_at Ckkk 77 10 5.5
In [36]: df_test
Out[36]:
sample1 sample2 sample3
probegenes
1415777_at Pnliprp1 20.1 10.00 22.3
1415805_at Clps …Run Code Online (Sandbox Code Playgroud) 对此还是陌生的,对不起,如果我问一些真正愚蠢的事情。Python有序词典和pandas系列有什么区别?
我能想到的唯一区别是,orderedDict在数据中可以有嵌套字典。这就是全部?那是真的吗?
使用一种与另一种之间会有性能差异吗?
我的项目是销售预测,大多数数据将是:{第1周:400个单位,第2周:550个单位} ...也许有序词典将是多余的,因为与第#周相比输入订单无关紧要?
再次抱歉,我的问题是愚蠢的,我只是在学习时尝试变得更彻底。
谢谢!
-斯蒂芬
我正在计算包含价格数据DataFrame中每一行的损益金额DataFrame。
逻辑如下:
holding_period。take_profit,则以该价格退出以获取利润。stop_loss,则以该价格退出,造成损失。take_profit或stop_loss看到的水平决定了我们是盈利还是亏损退出。我实现此目的的方法是使用pandas.rolling_apply,它将提供的函数应用到 中每个系列的滚动窗口上DataFrame。
鉴于rolling_apply为 中的每个行和列组合调用一个函数DataFrame,这是一个严重的瓶颈。
我想知道是否有更好的方法使用其他 pandas/numpy 功能来实现此目的?
这是当前的实现:
def potential_pnl(prices, side, periods, take_profit=np.nan, stop_loss=np.nan):
# set sign depending on direction of price movement required by BUY/SELL
if side == Side.SELL:
take_profit *= -1
else:
stop_loss *= -1
def period_potential_pnl(window):
# enter at the first price, rest of the …Run Code Online (Sandbox Code Playgroud) 我有2个案例要解析JSON首先是:
{
"post_filter_data": {
"Items": [
{
"ItemID": "50cb4e46b5d30b0002000009",
"ItemName": "Fruit salad test",
"ItemPrice": "122.0",
"ItemDescription": "test test",
"ItemImageUrl": "http://s3.amazonaws.com/menubis-mms-prototype-dev/menubis/assets/50cb4e64b5d30b0002000013/landing_page.jpg?1355501156"
},
{
"ItemID": "50d0870d910ef2000200000a",
"ItemName": "test new",
"ItemPrice": "120.0",
"ItemDescription": null,
"ItemImageUrl": "http://s3.amazonaws.com/menubis-mms-prototype-dev/menubis/assets/50d0871a910ef20002000015/Screenshot-2.png?1355843354"
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
其中Items是an NSArray并且它很容易解析,但是当只有一个对象时,我会通过异常来解析它.其次JSON是Items标签有一个对象:
{
"post_filter_data": {
"Items": {
"ItemID": "50d1e9cd9cfbd20002000016",
"ItemName": "test",
"ItemPrice": "120.0",
"ItemDescription": "test",
"ItemImageUrl": "http://s3.amazonaws.com/menubis-mms-prototype-dev/menubis/assets/50d1ea019cfbd20002000022/11949941671787360471rightarrow.svg.med.png?1355934209"
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的代码就在这里我在解析它:
NSDictionary *dictMenu=[responseDict valueForKey:@"post_filter_data"];
NSArray* subMenuArray=[dictMenu valueForKey:@"Items"];
Run Code Online (Sandbox Code Playgroud)
有什么方法可以检查出那valueForKey:@"Items"是什么Array或者Object.
我有一个pandas数据框的子集,其中包含我想使用statsmodel使用AR或ARIMA模型分析的时间序列:
data_sci = H_Clinton_social_vector.Florida
Run Code Online (Sandbox Code Playgroud)
数据如下所示:
Date
2015-09-28 587
2015-10-05 582
2015-10-12 606
2015-10-19 698
Run Code Online (Sandbox Code Playgroud)
我的AR模型是这样创建的,每周汇总时间序列:
ar_model = sm.tsa.AR(data_sci, freq='W')
ar_model
<statsmodels.tsa.ar_model.AR at 0x1178f5490>
Run Code Online (Sandbox Code Playgroud)
接下来,我想对AR参数进行最大似然估计(MLE)拟合,半年滞后:
ar_res = ar_model.fit(maxlag=26, method='mle')
Run Code Online (Sandbox Code Playgroud)
我得到以下结果:
correlate() got an unexpected keyword argument 'old behavior'
Run Code Online (Sandbox Code Playgroud)
由于correlate()参数,我不明白问题是什么,我认为这与数据的自动关联有关.我的数据中有很高的自相关性,所以这应该没问题.
我对stasmodels不太熟悉,并且喜欢从头开始编码AR或ARIMA模型.
我有一个坐标列表,可以使用半径距离度量计算所有点之间的距离矩阵.
协调来作为一个numpy.array形状(n, 2)的(latitude, longitude)对:
[[ 16.34576887 -107.90942116]
[ 12.49474931 -107.76030036]
[ 27.79461514 -107.98607881]
...
[ 12.90258404 -107.96786569]
[ -6.29109889 -107.88681145]
[ -2.68531605 -107.72796034]]
Run Code Online (Sandbox Code Playgroud)
我也可以沿着坐标序列隐含的路径提取距离,如下所示:
coordinates = np.deg2rad(coordinates)
lat, lng = coordinates[:, 0], coordinates[:, 1]
diff_lat = lat[:, None] - lat
diff_lng = lng[:, None] - lng
d = np.sin(diff_lat / 2) ** 2 + np.cos(lat[:, None]) * np.cos(lat) * np.sin(diff_lng / 2) ** 2
dist_matrix = 2 * 6371 * np.arcsin(np.sqrt(d))
np.diagonal(dist_matrix, …Run Code Online (Sandbox Code Playgroud) 我有一个大约有 370 列的数据框。我正在测试一系列假设,这些假设要求我使用模型的子集来拟合三次回归模型。我计划使用 statsmodels 对这些数据进行建模。
多项式回归过程的一部分涉及均值中心变量(从特定特征的每个案例中减去均值)。
我可以用 3 行代码做到这一点,但它似乎效率低下,因为我需要为六个假设复制这个过程。请记住,我需要从 statsmodel 输出中获取系数级别的数据,因此我需要保留列名。
这是数据的一瞥。这是我的假设检验之一所需的列子集。
i we you shehe they ipron
0 0.51 0 0 0.26 0.00 1.02
1 1.24 0 0 0.00 0.00 1.66
2 0.00 0 0 0.00 0.72 1.45
3 0.00 0 0 0.00 0.00 0.53
Run Code Online (Sandbox Code Playgroud)
这是表示居中并保留列名称的代码。
from sklearn import preprocessing
#create df of features for hypothesis, from full dataframe
h2 = df[['i', 'we', 'you', 'shehe', 'they', 'ipron']]
#center the variables
x_centered = preprocessing.scale(h2, with_mean='True', with_std='False')
#convert back into a …Run Code Online (Sandbox Code Playgroud) 我正在努力swarmplot与之合作pandas.我有一个numpy array名为SIAggs 的3D ,我用pandas这样切片:
rand_center = {('Random_dist'):SIAggs[:,:,1], ('Center_distance'):SIAggs[:,:,0]}
for key, value in rand_center.items():
rand_center[key] = pd.DataFrame(value)
sizes = {}
for i in range(size_iterations):
sizes.update({ (str(i+1)) : SIAggs[i,:,:] })
for key, value in sizes.items():
sizes[key] = pd.DataFrame(value)
df = pd.concat(sizes, rand_center, names = ['sizes', 'distance_measure'])
df.stack()
Run Code Online (Sandbox Code Playgroud)
哪,当我打印DataFrame给我时:
sizes 1 2 3
distance_measure 0 1 0 1 0 1
0 -2.1881 1.262 -2.7001 1.493 -2.1381 1.626
1 -2.3671 1.699 -2.4431 1.208 -2.4571 …Run Code Online (Sandbox Code Playgroud) 我有一个DataFrame包含日内价格/数量的数据:
time price volume
2015-04-15 10:10:00 10 500
2015-04-15 10:20:00 15 100
2015-04-15 10:30:00 20 70
2015-04-15 10:30:00 etc etc
Run Code Online (Sandbox Code Playgroud)
我需要得到一个标准价格 - 交易量表,其中顶部图表包含价格(常规线),底部图表包含交易量(条形图).
当然,两个图表应该共享同一个轴.
到目前为止,我想出了:
plt.figure(figsize=(20,15))
ax1=plt.subplot2grid((2,2),(0,0),colspan=2)
ax2=plt.subplot2grid((2,2),(1,0),colspan=2)
ax2.xaxis.set_major_locator(HourLocator(interval=3))
ax2.xaxis.set_major_formatter(DateFormatter('%H:%M'))
data.ix['2015-10-01': '2015-10-02','price'].plot(ax=ax1)
data.ix['2015-10-01': '2015-10-02','volume'].plot(ax=ax2, kind='bar')
Run Code Online (Sandbox Code Playgroud)
但是我为条形图获得了超密集的刻度标签(图表无法使用).
我怎样才能简单地指定每小时有一个小刻度,每3小时有一个主要刻度(这样图表仍然可读)?
python ×9
pandas ×7
numpy ×5
statsmodels ×2
distance ×1
haversine ×1
ios ×1
iphone ×1
matplotlib ×1
objective-c ×1
performance ×1
python-3.x ×1
scikit-learn ×1
seaborn ×1
series ×1
time-series ×1
xcode ×1