【发布时间】:2018-02-09 17:48:00
【问题描述】:
我有两个 DataFrames df1 和 df2 有很多列
df1 - [2756003 行 x 44 列]
df2 - [22035 行 x 11 列]
我需要将新列添加到 df2,其中目标列的平均值来自 df1 基于按结果分组(对于 df1 和 df2 中的相同列)
t1 = df1.groupby(['category', 'manufacturer'])
t2=t1[c1].mean()
str1='_'.join(col)
df2[c1+'_'+str1+'_mean']=t2[df2[['category','manufacturer']].as_matrix()].values
返回:
IndexError: arrays used as indices must be of integer (or boolean) type
t2 - 存储多索引系列,例如:
category manufacturer
1 2 0.000000
4 8.796840
10 2.312407
19 1.135094
24 4.355000
如果我使用现有索引,我会得到预期的结果
In [302]: t2[1, 2]
Out[302]: 0.0
但是如果我调用 t2[410, 332],其中 332 是制造商的 id,它出现在 df2 中而不出现在 df1 中,我会得到 p>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我想得到 NaN 而不是像我们得到的那样
df2['manufacturer'].map(t2)
如果只有一列。
【问题讨论】:
标签: python pandas numpy multi-index