每行的元素乘法

时间:2017-03-04 12:54:55

标签: pandas dataframe series multiplying elementwise-operations

我有两个DataFrame个对象,我想在每行上应用元素乘法:

df_prob_wc.shape  # (3505, 13)
df_prob_c.shape   # (13, 1)

我以为我可以用DataFrame.apply()

来做
df_prob_wc.apply(lambda x: x.multiply(df_prob_c), axis=1)

给了我:

TypeError: ("'int' object is not iterable", 'occurred at index $')

df_prob_wc.apply(lambda x: x * df_prob_c, axis=1)

给了我:

TypeError: 'int' object is not iterable

但它没有用。 但是,我可以这样做:

df_prob_wc.apply(lambda x: x * np.asarray([1,2,3,4,5,6,7,8,9,10,11,12,13]), axis=1)

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

根据Series df_prob_c创建的iloc似乎需要多个:{/ p>

df_prob_wc = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df_prob_wc)
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

df_prob_c = pd.DataFrame([[4,5,6,1,2,3]])
#for align data same columns in both df
df_prob_c.index = df_prob_wc.columns
print (df_prob_c)
   0
A  4
B  5
C  6
D  1
E  2
F  3

print (df_prob_wc.shape)
(3, 6)
print (df_prob_c.shape)
(6, 1)
print (df_prob_c.iloc[:,0])
A    4
B    5
C    6
D    1
E    2
F    3
Name: 0, dtype: int64

print (df_prob_wc.mul(df_prob_c.iloc[:,0], axis=1))
    A   B   C  D   E   F
0   4  20  42  1  10  21
1   8  25  48  3   6  12
2  12  30  54  5  12   9

另一个解决方案是numpy array多个,只需要[:,0]用于选择:

print (df_prob_wc.mul(df_prob_c.values[:,0], axis=1))

    A   B   C  D   E   F
0   4  20  42  1  10  21
1   8  25  48  3   6  12
2  12  30  54  5  12   9

另一个DataFrame.squeeze的解决方案:

print (df_prob_wc.mul(df_prob_c.squeeze(), axis=1))
    A   B   C  D   E   F
0   4  20  42  1  10  21
1   8  25  48  3   6  12
2  12  30  54  5  12   9
相关问题