简体   繁体   中英

Replace a subset pandas dataframe with rows and columns via a numpy array

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.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM