向 pandas 数据框添加空值 [英] Adding null values to a pandas dataframe

查看:88
本文介绍了向 pandas 数据框添加空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于创建JSON的熊猫数据框,而JSON又用于显示高位图表.

I have a pandas dataframe that is used to create a JSON which in turn is used to display a highcharts chart.

熊猫数据框:

Date        colA    colB
12-Sep-14   20      40
13-Sep-14   50      10
14-Sep-14   12      -20
15-Sep-14   74      43

是否可以将一些colA和colB值更改为null.原因是我最终需要一个看起来像这样的JSON:

Is there a way to change some of the colA and colB values to null. The reason for this is that I ultimately need a JSON that looks something like this:

[
    [12-Sep-14, 20, 40],
    [13-Sep-14, null, null],
    [14-Sep-14, 12, -20],
    [15-Sep-14, 74, 43]
]

原因是我需要一个高图图表,其中某些绘图点为空白.为此,请指定日期,后跟null.

The reason for this is that I require a highcharts chart where certain plot points are blank. To do this, you specify the date followed by null.

因此,我需要以某种方式更新pandas数据框中的某些值,以便一旦我使用.to_json()将其转换为JSON,则json将包含上述示例中指定的空值.

So I need to somehow update certain values in the pandas dataframe so that once I convert it to a JSON using .to_json() then the json will contain the specified null values as per the example above.

谢谢您的建议.

推荐答案

这项工作有效吗?

import pandas as pd
# Read in data frame from clipboard
df = pd.read_clipboard()
df = df.replace(df.iloc[1][1:],'null')

        Date  colA  colB
0  12-Sep-14    20    40
1  13-Sep-14  null  null
2  14-Sep-14    12   -20
3  15-Sep-14    74    43

在这里,df.iloc [1]可以访问第1行

Here, df.iloc[1] gives access to row 1

最后,

df.to_json(orient='values').replace("\"","")

提供不带"的json

gives json without the ""

[[12-Sep-14,20,40],[13-Sep-14,null,null],[14-Sep-14,12,-20],[15-Sep-14,74,43]]

这篇关于向 pandas 数据框添加空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆