Reputation: 499
I would like to use a numpy array to replace a subset dataframe from a pandas dataframe.
For example:
a pandas dataframe df
.
df_subset = df.loc[[1,3,5,7,9], ["A", "B", "C"]]
Here, the subset dataframe has a dimension of (5, 3)
:
And below is the numpy array example with the same shape as the subset dataframe I would like to replace to:
replace_value = np.array([[1, 2, 3], [4, 4, 4], [1, 6, 8], [1, 3, 6], [8, 0, 1]])
Is there any approach similar to:
df_subset.values = replace_value
What I hope is that the value I replaced will directly change the original values in df
. Which means that if I subset df
with the same indice and columns again, I will get the exact values as the numpy array I assigned as replace_value
above.
Upvotes: 1
Views: 720
Reputation: 24304
You can try via loc
accessor:
df.loc[[1,3,5,7,9], ["A", "B", "C"]]=replace_value
#just like you grabbed values you can also assign that back like that
sample data:
df=pd.DataFrame(np.random.randn(25,3),columns=["A", "B", "C"])
replace_value = np.array([[1, 2, 3], [4, 4, 4], [1, 6, 8], [1, 3, 6], [8, 0, 1]])
df.loc[[1,3,5,7,9], ["A", "B", "C"]]=replace_value
Upvotes: 6