我有一个三维的numpy数组 public void saveProductsDataToFile(File file) {
try {
JAXBContext context = JAXBContext.newInstance(ProductListWrapper.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
ProductListWrapper wrapper = new ProductListWrapper();
wrapper.setProducts(products);
m.marshal(wrapper, file);
setProductFilePath(file);
} catch (Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Fail!");
alert.setHeaderText("Can't save data!");
alert.setContentText("Can't save data to:\n" + file.getPath() );
alert.showAndWait();
}
。我想要
public class Product {
private StringProperty name;
private IntegerProperty amount;
private ProductType type;
private BooleanProperty ifConttainsPreservatives;
public void setType(ProductType type) {
this.type = type;
}
public String getName() {
return name.get();
}
public boolean isIfConttainsPreservatives() {
return ifConttainsPreservatives.get();
}
public void setName(String name) {
this.name.set(name);
}
public void setAmount(int amount) {
this.amount.set(amount);
}
public void setIfConttainsPreservatives(boolean ifConttainsPreservatives) {
this.ifConttainsPreservatives.set(ifConttainsPreservatives);
}
public ProductType getType() {
return type;
}
public BooleanProperty ifConttainsPreservativesProperty() {
return ifConttainsPreservatives;
}
public StringProperty nameProperty() {
return name;
}
public int getAmount() {
return amount.get();
}
public IntegerProperty amountProperty() {
return amount;
}
public Product(int amount, boolean ifContainsPreservatives, String name, ProductType type) {
this.name = new SimpleStringProperty(name);
this.amount = new SimpleIntegerProperty(amount);
this.ifConttainsPreservatives = new SimpleBooleanProperty(ifContainsPreservatives);
this.type =type;
}
public Product() {
}
}
每个A
。
我怎样才能在numpy中优雅地做到这一点?是否可以避免所有A[i, i, :] = 1.0
循环?
答案 0 :(得分:2)
方法#1 您可以使用np.eye
创建对角线遮罩,然后使用布尔索引来指定 -
mask = np.eye(A.shape[0], dtype=bool)
A[mask] = 1.0
方法#2 使用基于整数的索引 -
r = np.arange(A.shape[0])
A[r,r] = 1.0
方法#3 重塑为2D
,然后分配到行中 -
n = A.shape[0]
A.reshape(-1,A.shape[-1])[np.arange(n)*(n+1)] = 1.0