Skip to main content
 首页 » 编程设计

python之Pandas DataFrame 乘以数组

2025年05月04日11lvdongjie

数据框

A B C 
1 2 3 
2 4 6 

array = [1,10,100] 

结果:

A   B   C 
1   2   3 
2   4   6 
10  20  30 
20  40  60 
100 200 300 
200 400 600 

数组和数据帧长度可以是任意大小,不一定相同。

我已经使用了 FOR 循环,如果我有大数据帧或数据帧太多,这太慢了。

下面是我的示例片段:

for i in array: 
    pr[pr.select_dtypes(include=['number']).columns] *= i 
    fdf = np.concat([fdf,pr],axis=0) 

有没有更快的方法来做到这一点。我正在处理多个数据帧,在此操作之后需要连接起来。

请您参考如下方法:

mult = df.values * np.array([1,10,100])[:, np.newaxis, np.newaxis] 
pd.DataFrame(mult.reshape((-1, 3)), columns=df.columns) 
 
     A    B    C 
0    1    2    3 
1    2    4    6 
2   10   20   30 
3   20   40   60 
4  100  200  300 
5  200  400  600