简体   繁体   English

通过numpy数组用行和列替换子集pandas数据框

[英]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.我想使用 numpy 数组来替换 Pandas 数据帧中的子集数据帧。

For example: a pandas dataframe df .例如:熊猫数据帧df

df_subset = df.loc[[1,3,5,7,9], ["A", "B", "C"]]

Here, the subset dataframe has a dimension of (5, 3) :这里,子集数据帧的维度为(5, 3)

And below is the numpy array example with the same shape as the subset dataframe I would like to replace to:下面是 numpy 数组示例,其形状与我想替换为的子集数据帧相同:

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 .我希望我替换的值会直接改变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.这意味着,如果我再次使用相同的索引和列对df进行子集化,我将获得与上面指定为replace_value的 numpy 数组相同的确切值。

You can try via loc accessor:您可以通过loc访问器尝试:

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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