1

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.

0

1 Answer 1

6

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Yes! This worked! Thank you! I was stuck in replacing values need to use .loc[ ].values. :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.