Python 每行乘法-加速
我有非常慢的代码: 一个名为Python 每行乘法-加速,python,pandas,Python,Pandas,我有非常慢的代码: 一个名为tmp的数据帧,具有多索引(日期和id),大约有2.000.000行和2列(V1、V2) 而ref包含大约5000行250列 C1 C2 ... C250 ID 1 0.2 0.3 ... 0.1 2 1.2 1.3 ... 0.0 预期结果应具有以下形式: C1 C2 ... C250 Date 2000-01-01 xx xx ... xx 我试过: sum1 =
tmp
的数据帧,具有多索引(日期和id),大约有2.000.000行和2列(V1、V2)
而ref
包含大约5000行250列
C1 C2 ... C250
ID
1 0.2 0.3 ... 0.1
2 1.2 1.3 ... 0.0
预期结果应具有以下形式:
C1 C2 ... C250
Date
2000-01-01 xx xx ... xx
我试过:
sum1 = pd.DataFrame(0, index=idx1, columns=idx2)
sum2 = pd.DataFrame(0, index=idx1, columns=idx2)
def gen(row):
i1 = row.name[0] # date
i2 = row.name[1] # id
sum1.loc[i1] += ref.loc[i2] * row['V1']
sum2.loc[i1] += ref.loc[i2] * row['V2']
tmp.apply( gen , axis=1)
有没有可能加快速度?我用Cython试用过,但在3小时后关闭了应用程序…我想你需要,然后通过以下方式删除多索引的级别id
:
然后,如果需要列:
我认为您需要,然后通过以下方式删除多索引的id
:
然后,如果需要列:
您可以添加一些示例数据吗?您可以添加一些示例数据吗?I receive:ValueError:无法在没有指定级别和名称重叠的情况下加入。我需要在gen函数中调用它吗?我认为apply
非常慢,问题在于测试数据还是仅限于real?我将测试数据添加到答案中。谢谢,索引名称不同。I receive:ValueError:无法加入,没有指定级别,也没有重叠的名称。我需要在gen函数中调用它吗?我认为apply
非常慢,问题在于测试数据还是仅限于real?我添加测试数据来回答。谢谢,索引名称不同
sum1 = pd.DataFrame(0, index=idx1, columns=idx2)
sum2 = pd.DataFrame(0, index=idx1, columns=idx2)
def gen(row):
i1 = row.name[0] # date
i2 = row.name[1] # id
sum1.loc[i1] += ref.loc[i2] * row['V1']
sum2.loc[i1] += ref.loc[i2] * row['V2']
tmp.apply( gen , axis=1)
tmp = pd.DataFrame({'date':pd.date_range('2000-01-01', periods=3),
'id':[1,2,1],
'V1':[.3,.3,.1],
'V2':[.1,.1,.1]}).set_index(['date','id'])
print (tmp)
V1 V2
date id
2000-01-01 1 0.3 0.1
2000-01-02 2 0.3 0.1
2000-01-03 1 0.1 0.1
ref = pd.DataFrame({'C1':[.2,1.2],'C2':[.3,1.3], 'C250':[.1,0.0]}, index=[1,2])
ref.index.name = 'id'
print (ref)
C1 C2 C250
id
1 0.2 0.3 0.1
2 1.2 1.3 0.0
sum1 = ref.mul(tmp['V1'], axis=0).reset_index(level=1, drop=True)
sum2 = ref.mul(tmp['V2'], axis=0).reset_index(level=1, drop=True)
print (sum1)
C1 C2 C250
date
2000-01-01 0.06 0.09 0.03
2000-01-02 0.36 0.39 0.00
2000-01-03 0.02 0.03 0.01
print (sum2)
C1 C2 C250
date
2000-01-01 0.02 0.03 0.01
2000-01-02 0.12 0.13 0.00
2000-01-03 0.02 0.03 0.01
sum1 = ref.mul(tmp['V1'], axis=0).reset_index(level=1, drop=True).sum(axis=1).to_frame('SUM')
sum2 = ref.mul(tmp['V2'], axis=0).reset_index(level=1, drop=True).sum(axis=1).to_frame('SUM')
print (sum1)
SUM
date
2000-01-01 0.18
2000-01-02 0.75
2000-01-03 0.06
print (sum2)
SUM
date
2000-01-01 0.06
2000-01-02 0.25
2000-01-03 0.06