【问题标题】:Element wise multiplication of each row每行的元素乘法
【发布时间】:2017-03-04 12:54:55
【问题描述】:

我有两个 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)

我在这里做错了什么?

【问题讨论】:

    标签: pandas dataframe series multiplication elementwise-operations


    【解决方案1】:

    看来您需要多个 by Series 使用 df_prob_c by iloc 创建:

    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
    

    【讨论】:

    • 不错!就我而言,我只需要转换 df_prob_c 就可以了:df_prob_wc.mul(df_prob_c.T.iloc[0], axis=1)。我想出的解决方案是df_prob_wc.apply(lambda x: x * df_prob_c.T.as_matrix()[0], axis=1),但你的解决方案当然要简单得多。谢谢!
    • 是的,在这里申请要慢得多,最好使用mul
    • 现在我改变解决方案,你需要df_prob_wc.mul(df_prob_c.iloc[:, 0], axis=1)
    • 感谢您的解释!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 2020-07-24
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多