'Add/Sum values of a column vector to a matrix with pandas
I have 2 dataframes (without headers or index). One is of size 100x20 (Dataframe A) and the other of size 100x1 (Dataframe B). I would like to add the values of Dataframe B to the first 5 columns in Dataframe A. I tried to do this with
C = A.iloc[:,:5].add(B,axis=0)
Now C is of size 100X5 but I get A[:,0]+B for the first column alone and the other 4 columns in C is NaN. What am I doing wrong?
Solution 1:[1]
This is because of index alignement. DataFrames necessarily have indexes. Here B has index 0, so when aligned with A during addition, only the column 0 of A is used.
Use an array to bypass it:
C = A.iloc[:,:5].add(B.to_numpy(), axis=0)
Or slice B as Series:
A.iloc[:,:5].add(B[0], axis=0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
