Swift 2.2
如何为data = [['aaa', 1, 110, 2, 0],
['bbb', 0, 123, 10, 11],
['ccc', 0, 134, 1, 2],
['ddd', 1, 333, 2, 3],
['eee', 1, 444, 2, 0]]
data2 = [['Average', 0.1, 0.2, 0.3],
['Mean', 0.5, 0.5, 0.5],
['denom', 0.3, 0.35, 0.4]]
df1 = pd.DataFrame(data=data, columns=['user', 'A', 'A1', 'B', 'C'])
df1.set_index(['user'], inplace=True)
df2 = pd.DataFrame(data=data2, columns=['index', 'A', 'B', 'C'])
df2.set_index(['index'], inplace=True)
的每一行df1
和df2.loc['denom']
的相应列之间相乘,并对行进行求和。
df1
结果将类似于:
A A1 B C
user
aaa 1 110 2 0
bbb 0 123 10 11
ccc 0 134 1 2
ddd 1 333 2 3
eee 1 444 2 0
A B C
index
Average 0.1 0.20 0.3
Mean 0.5 0.50 0.5
denom 0.3 0.35 0.4
答案 0 :(得分:3)
那基本上是一个点积。所以,一种方法是 -
df1[df2.columns].dot(df2.loc['denom'])
示例运行 -
In [55]: df1
Out[55]:
A A1 B C
user
aaa 1 110 2 0
bbb 0 123 10 11
ccc 0 134 1 2
ddd 1 333 2 3
eee 1 444 2 0
In [56]: df2
Out[56]:
A B C
index
Average 0.1 0.20 0.3
Mean 0.5 0.50 0.5
denom 0.3 0.35 0.4
In [57]: df1[df2.columns].dot(df2.loc['denom'])
Out[57]:
user
aaa 1.00
bbb 7.90
ccc 1.15
ddd 2.20
eee 1.00
dtype: float64
答案 1 :(得分:3)
默认情况下,将系列(df2.loc['denom']
)与DataFrame(df1
)相乘会使系列元素与列匹配,因此请执行所需操作:
In [74]: df1 * df2.loc['denom']
Out[74]:
A A1 B C
user
aaa 0.3 NaN 0.70 0.0
bbb 0.0 NaN 3.50 4.4
ccc 0.0 NaN 0.35 0.8
ddd 0.3 NaN 0.70 1.2
eee 0.3 NaN 0.70 0.0
(以上更明确的版本是:df1.mul(df2.loc['denom'], axis=1)
)
要以期望的结果结束,您可以在不同的列上对上述内容求和:
In [75]: (df1 * df2.loc['denom']).sum(axis=1)
Out[75]:
user
aaa 1.00
bbb 7.90
ccc 1.15
ddd 2.20
eee 1.00
dtype: float64