首页 \ 问答 \ 将常量numpy数组值分配给pandas dataframe列(Assign constant numpy array value to pandas dataframe column)

将常量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
更新时间:2022-07-06 19:07

最满意答案

您可以使用以下代码编写带有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 own 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);
    }
}

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中编写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
  • MVC中的JsonResult实际上并没有使用JSON.NET,这就是为什么[JsonIgnore]不起作用的原因。 相反,它使用JavaScriptSerializer类。 要使JavaScriptSerializer跳过属性,可以使用[ScriptIgnore]属性上的[ScriptIgnore]属性。 另一种方法是创建一个自定义ActionResult ,它使用JSON.NET的JsonConvert来序列化该对象,然后该对象将[JsonIgnore]属性。 The JsonResult in MVC ...
  • 您可以使用以下代码编写带有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 ...
  • 这是一个有趣的问题。 我的回答大量借鉴了您提供的链接,但检查了定义“高级内容”的自定义属性(用户支付的费用): 就像你的链接一样,我已经定义了一个类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 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)