I have a reference dataframe df1 with 7 columns and 7 rows. The columns and indices are both 0-7. All values are 0. (That is being said, I have a 7x7 dataframe of 49 0s.)
I have another smaller dataframe df2 with n columns and n rows, where n is a random number <=7. The columns and indices are n numbers in the range of [0, 7]. The values are random values.
You can see the examples below.
What I want to do is replace the 0s in df1 where df2 has the same index+column, and keep the 0s in df1 where there is no match in df2.
This is df1
# create a 7*7 dataframe of 0s
df1 = pd.DataFrame(np.zeros((7, 7)))
print(df1.columns)
print(df1.index)
df1
This is df2
# create random n-dimention-dataframe, where n must <= 6
import random
n = random.randrange(1, 7)
arr = np.random.randint(500, size=(n, n))
df2 = pd.DataFrame(arr, index = random.sample(range(0, 7), n), columns = random.sample(range(0, 7), n))
print(df2.columns)
print(df2.index)
df2
So, eventually, I want something like this. I made this example table in excel because that's why I'm here - I want a dataframe like this - the index and column are the same and in the same order as df1; some values come from df2; unmatched cells remain 0. A reminder that it needs to be automated to detect what column/index numbers are in df2 to make the replacement, as df2 comes from random generators.
Thanks a lot if you could please help!!
Aucun commentaire:
Enregistrer un commentaire