【问题标题】:python alternative solution scipy spatial distance, current solution returns MemoryErrorpython替代解决方案scipy空间距离,当前解决方案返回MemoryError
【发布时间】:2017-04-18 09:37:37
【问题描述】:

我有一个这样的数据框和函数:

df = pandas.DataFrame({'Car' : ['BMW_1', 'BMW_2', 'BMW_3', 'WW_1','WW_2','Fiat_1', 'Fiat_2'],
                       'distance'   : [10,25,22,24,37,33,49]})

def my_func(x,y):
   z = 2x + 3y
   return z

我想获得汽车行驶距离的成对组合,并在 my_func 中使用它们。但是有两个条件,x和y不能是同一个品牌,组合不能重复。期望的输出是这样的:

Car      Distance   Combinations                                
0  BMW_1   10         (BMW_1,WW_1),(BMW_1,WW_2),(BMW_1,Fiat_1),(BMW_1,Fiat_1)
1  BMW_2   25         (BMW_2,WW_1),(BMW_2,WW_2),(BMW_2,Fiat_1),(BMW_2,Fiat_1)
2  BMW_3   22         (BMW_3,WW_1),(BMW_3,WW_2),(BMW_3,Fiat_1),(BMW_3,Fiat_1)
3  WW_1    24         (WW_1, Fiat_1),(WW_1, Fiat_2)
4  WW_2    37         (WW_2, Fiat_1),(WW_2, Fiat_2)
5  Fiat_1  33         None
6  Fiat_2  49         None

//Output
[120, 134, 156, 178]
[113, 145, 134, 132]
[114, 123, 145, 182]
[153, 123] 
[120, 134] 
None 
None 

下一步我想从每个品牌的“输出”行的数组中获取最大数量。最终数据应该是这样的

  Car  Max_Distance
0 BMW  178
1 WW   153
2 Fiat None

MaxU 在这里给了我一个很好的答案:python pandas, a function will be applied to the combinations of the elements in one row based on a condition on the other row

但由于我的数据集非常大,尽管我在超级计算机中运行我的代码,但我一直收到内存错误。有没有更有效的方法来实现这一目标?也许将组合保存到数据库然后获得最大值?

【问题讨论】:

    标签: python pandas scipy out-of-memory


    【解决方案1】:

    所以这是第一件事的代码:

    import pandas as pd
    import itertools as it
    
    df = pd.DataFrame({'Car' : ['BMW_1', 'BMW_2', 'BMW_3', 'WW_1','WW_2','Fiat_1', 'Fiat_2'],
                           'Distance'   : [10,25,22,24,37,33,49]})
    
    
    cars = df['Car'].tolist()
    combos = [a for a in list(it.combinations(cars,2)) if a[0].split('_')[0] != a[1].split('_')[0]]
    
    maps_combos = {car: [combo for combo in combos if combo[0] == car] for car in cars}
    values = {k:v for k,v in df[['Car', 'Distance']].as_matrix()}
    maps_values = {i: [2*value[0] + 3*value[1] for value in j] for i, j in {k: [map(lambda x: values[x], item) for item in v] for k, v in maps_combos.items()}.items() if j}
    
    df['Combinations'] = df['Car'].map(maps_combos)
    df['Output'] = df['Car'].map(maps_values)
    

    至于最大值,我需要休息一下:)

    附:我不确定我是否得到了正确的距离乘法函数。

    编辑

    这个最大的事情(肯定可以做得更好):

    df['Max'] = df['Output'].fillna(0).apply(lambda x: max(x) if x != 0 else np.nan)
    df['Brand'] = df['Car'].apply(lambda x: x.split('_')[0])
    brand_max = df[['Brand', 'Max']].groupby('Brand').max()
    

    【讨论】:

    • 函数没那么重要 :) 让我看看会不会再出现内存错误
    猜你喜欢
    • 1970-01-01
    • 2020-08-29
    • 2018-03-05
    • 2011-04-13
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    相关资源
    最近更新 更多