将常量numpy数组值分配给pandas dataframe列(Assign constant numpy array value to pandas dataframe column)
我想为pandas dataframe列分配常量numpy数组值。
这是我试过的:
import pandas as pd import numpy as np my_df = pd.DataFrame({'col_1': [1,2,3], 'col_2': [4,5,6]}) my_df['new'] = np.array([]) # did not work my_df['new'] = np.array([])*len(df) # did not work
这是有效的:
my_df['new'] = my_df['new'].apply(lambda x: np.array([]))
我很好奇为什么它适用于简单的标量,但不适用于numpy数组。 是否有更简单的方法来分配numpy数组值?
I would like to assign constant numpy array value to pandas dataframe column.
Here is what I tried:
import pandas as pd import numpy as np my_df = pd.DataFrame({'col_1': [1,2,3], 'col_2': [4,5,6]}) my_df['new'] = np.array([]) # did not work my_df['new'] = np.array([])*len(df) # did not work
Here is what worked:
my_df['new'] = my_df['new'].apply(lambda x: np.array([]))
I am curious why it works with simple scalar, but does not work with numpy array. Is there simpler way to assign numpy array value?
原文:https://stackoverflow.com/questions/46774106
最满意答案
您可以使用以下代码编写带有Java代码的Custom Serializer和De-Serializer:
class CustomSerializer extends JsonSerializer<ARow> { @Override public Class<ARow> handledType() { return ARow.class; } public void serialize(ARow value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("ounc", value.ounces.toLowerCase()); //Do this for all of your relevant properties.. jgen.writeEndObject(); }
}
并向杰克逊注册此自定义序列化器:
ObjectMapper m = new ObjectMapper(); SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null)); testModule.addSerializer(new CustomSerializer()); m.registerModule(testModule);
要使用Spring的
MappingJacksonJsonView
您需要扩展自己的ObjectMapper
public class MyCustomObjectMapper extends ObjectMapper { public MyCustomObjectMapper() { SimpleModule module = new SimpleModule("My Module", new Version(1, 0, 0, "SNAPSHOT")); module.addSerializer(new CustomSerializer()); module.addSerializer(new CustomSerializer2()); // etc this.registerModule(module); } }
为它创建一个bean
<bean id="myCustomObjectMapper" class="com.foo.proj.objectmapper.MyCustomObjectMapper"/>
并将其注入
MappingJacksonJsonView
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"> <property name="objectMapper" ref="myCustomObjectMapper"/> </bean>
You can write a Custom Serializer and De-Serializer, with Java code, along these lines:
class CustomSerializer extends JsonSerializer<ARow> { @Override public Class<ARow> handledType() { return ARow.class; } public void serialize(ARow value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeStringField("ounc", value.ounces.toLowerCase()); //Do this for all of your relevant properties.. jgen.writeEndObject(); }
}
and to register this Custom Serializer with Jackson:
ObjectMapper m = new ObjectMapper(); SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null)); testModule.addSerializer(new CustomSerializer()); m.registerModule(testModule);
To set this up with Spring's
MappingJacksonJsonView
you will need to extend your ownObjectMapper
public class MyCustomObjectMapper extends ObjectMapper { public MyCustomObjectMapper() { SimpleModule module = new SimpleModule("My Module", new Version(1, 0, 0, "SNAPSHOT")); module.addSerializer(new CustomSerializer()); module.addSerializer(new CustomSerializer2()); // etc this.registerModule(module); } }
Create a bean for it
<bean id="myCustomObjectMapper" class="com.foo.proj.objectmapper.MyCustomObjectMapper"/>
And inject it into your
MappingJacksonJsonView
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"> <property name="objectMapper" ref="myCustomObjectMapper"/> </bean>
相关问答
更多-
你可以通过实现一个自定义的IContractResolver并在序列化过程中使用它来做到这一点。 如果您DefaultContractResolver ,则这变得非常容易: class WritablePropertiesOnlyResolver : DefaultContractResolver { protected override IList
CreateProperties(Type type, MemberSerialization memberSeriali ... -
好的,我想我在javadoc中发现并明确提到了这个问题。 (杰克逊文档不容易通过)。 另外,从Jackson 1.9开始,如果这是与属性相关的唯一注释,它也会导致整个属性被忽略:也就是说,如果setter具有此注释并且getter没有注释,则getter也会被有效忽略。 不同的访问者仍有可能使用不同的注释; 所以如果只有“getter”被忽略,其他访问器(setter或field)将需要显式注释来防止忽略(通常是JsonProperty)。 Ok, I think I found and explicit ...
-
尝试在你的课堂中使用@JsonIgnore和@JsonProperty ,如下所示: private String password; @JsonIgnore public String getPassword() { return password; } @JsonProperty public void setPassword(String password) { this.password = password; } Try using both @JsonIgnore and ...
-
您可以通过将Json Filter与FilterProvider一起使用来实现此目的 使用@JsonFilter注释为POJO分配过滤器名称。 在序列化之前,将SimpleBeanPropertyFilter的实例附加到过滤器名称。 该类有两种工厂方法,用于根据属性名称工作的过滤器。 以下是注释声明的示例: @JsonFilter("filterByName") public class So { public String alwaysWrite = "alwaysWriteValue"; ...
-
Spring MVC Jackson Json @JsonIgnore以编程方式(Spring MVC Jackson Json @JsonIgnore programatically)[2023-01-31]
一种解决方案是提供自定义(反)序列化器,您可以在特定条件下删除/添加字段。 在Spring中编写JSON反序列化器或扩展它的正确方法 One solution whould be to provide a custom (de)serializer where you can remove/add fields on specific conditions. Right way to write JSON deserializer in Spring or extend it -
JsonIgnore无法在System.Web.Mvc.Controller中工作(JsonIgnore not working in System.Web.Mvc.Controller)[2022-01-29]
MVC中的JsonResult实际上并没有使用JSON.NET,这就是为什么[JsonIgnore]不起作用的原因。 相反,它使用JavaScriptSerializer类。 要使JavaScriptSerializer跳过属性,可以使用[ScriptIgnore]属性上的[ScriptIgnore]属性。 另一种方法是创建一个自定义ActionResult ,它使用JSON.NET的JsonConvert来序列化该对象,然后该对象将[JsonIgnore]属性。 The JsonResult in MVC ... -
MappingJacksonJsonView:忽略不使用@JsonIgnore的字段(MappingJacksonJsonView: ignore fields without using @JsonIgnore)[2024-05-14]
您可以使用以下代码编写带有Java代码的Custom Serializer和De-Serializer: class CustomSerializer extends JsonSerializer{ @Override public Class handledType() { return ARow.class; } public void serialize(ARow value, JsonGenerator jgen, SerializerProvider provi ... -
JsonIgnore属性条件模拟但不是ShouldSerialize(JsonIgnore attribute conditional analog but not ShouldSerialize)[2022-03-20]
这是一个有趣的问题。 我的回答大量借鉴了您提供的链接,但检查了定义“高级内容”的自定义属性(用户支付的费用): 就像你的链接一样,我已经定义了一个类Foo ,它将被序列化。 它包含一个子对象PremiumStuff ,它包含只有在用户付费时才应序列化的东西。 我已使用自定义属性PremiumContent标记此子对象,该属性也在此代码段中定义。 然后我使用了一个继承自DefaultContractResolver的自定义类,就像链接一样,但是在这个实现中,我正在检查每个属性的自定义属性,并且仅当属性被标记为 ... -
不要使用@JsonIgnore,而是使用@ApiResourceProperty : @ApiResourceProperty提供了对API中公开资源属性的方式的更多控制。 您可以在属性getter或setter上使用它来从API资源中省略该属性。 如果字段是私有的,您也可以在字段本身上使用它,以在API中公开它。 您还可以使用此批注更改API资源中的属性名称。 @ApiResourceProperty(ignored = AnnotationBoolean.TRUE) public String getB ...
-
password和salt都标记为@JsonProperty ,它优先于setter和getter上的ignore。 我想如果删除JsonPropety注释(或用JsonIgnore替换它),那么你想要忽略的那些字段实际上会被忽略。 password and salt are both labeled @JsonProperty, which takes precedence over the ignore on the setter and getter. I think if you remove th ...