I have 2 arrays; one is small array and second is big array as follows,
import pandas as pd
import numpy as np
dat1 = np.array([2, 3 ,4 ,4 ,3 ,2, 2, 4 ,3 ,4 ,4, 3])
dat2 = np.array([1, 4 ,4, 4, 2 ,1, 3 ,3 ,2, 3, 3, 1])
small_array = pd.crosstab(dat1, dat2)
big_array = pd.DataFrame(np.zeros(6*6).reshape(6,6), columns=[1,3,4,2,6,5], index=[3,4,1,2,5,6])
Now I want to place small_array
into big_array
matching the rownames and colnames between both arrays.
Is there any easy way to perform this?
Any pointer will be very helpful
CodePudding user response:
You can update
big_array
in-place:
big_array.update(small_array)
print(big_array)
If you want to create a new DataFrame, you can use combine_first
:
out = small_array.combine_first(big_array)
Output:
1 3 4 2 6 5
3 1.0 0.0 1.0 2.0 0.0 0.0
4 0.0 3.0 2.0 0.0 0.0 0.0
1 0.0 0.0 0.0 0.0 0.0 0.0
2 2.0 1.0 0.0 0.0 0.0 0.0
5 0.0 0.0 0.0 0.0 0.0 0.0
6 0.0 0.0 0.0 0.0 0.0 0.0
CodePudding user response:
Let us try reindex_like
out = small_array.reindex_like(big_array).fillna(0)
Out[494]:
1 3 4 2 6 5
3 1.0 0.0 1.0 2.0 0.0 0.0
4 0.0 3.0 2.0 0.0 0.0 0.0
1 0.0 0.0 0.0 0.0 0.0 0.0
2 2.0 1.0 0.0 0.0 0.0 0.0
5 0.0 0.0 0.0 0.0 0.0 0.0
6 0.0 0.0 0.0 0.0 0.0 0.0