1

我想使用平行坐标图绘制某些分析的结果。找到了一个使用 protovis http://mbostock.github.io/protovis/ex/cars.html制作的精彩示例,我正在尝试重新排列我的数据以根据示例复制数据文件的结构(cars.js)。因此,我的dataframe结构:

                    north   ch  wwr  ach  tmin  tmax  B1_EMS_DH26
Job_ID                                                           
EP_P1203_000000000    0.0  2.5   40  4.0    24    25       1272.2
EP_P1203_000000001    0.0  2.5   40  4.0    24    26       1401.9
EP_P1203_000000002    0.0  2.5   40  4.0    24    27       1642.3

应转换为以下内容:

var results = [{
    name: "EP_P1203_000000000",
    north: 0.0,
    ch: 2.5,
    wwr: 40,
    ach: 4.0,
    tmin: 24,
    tmax: 25,
    origin: 1272.2
  },
  {
    name: "EP_P1203_000000001",
    north: 0.0,
    ch: 2.5,
    wwr: 40,
    ach: 4.0,
    tmin: 24,
    tmax: 26,
    origin: 1401.9
  },
  {
    name: "EP_P1203_000000002",
    north: 0.0,
    ch: 2.5,
    wwr: 40,
    ach: 4.0,
    tmin: 24,
    tmax: 27,
    origin: 1272.3
  },
  {
    name: "EP_P1203_000000003",
    north: 0.0,
    ch: 2.5,
    wwr: 40,
    ach: 4.0,
    tmin: 24,
    tmax: 28,
    origin: 1642.3
  },
];

除了将我的列替换B1_EMS_DH26origin(图表似乎使用它来设置线条颜色)之外,我不想手动切片行和替换符号。

使用该dataframe.to_json命令返回一行:

{
  "EP_P1203_000000000": {
    "north": 0.0,
    "ch": 2.5,
    "wwr": 40,
    "ach": 4.0,
    "tmin": 24,
    "tmax": 25,
    "B1_EMS_DH26": 1272.2
  },
  "EP_P1203_000000001": {
    "north": 0.0,
    "ch": 2.5,
    "wwr": 40,
    "ach": 4.0,
    "tmin": 24,
    "tmax": 26,
    "B1_EMS_DH26": 1401.9
  },
  "EP_P1203_000000002": {
    "north": 0.0,
    "ch": 2.5,
    "wwr": 40,
    "ach": 4.0,
    "tmin": 24,
    "tmax": 27,
    "B1_EMS_DH26": 1642.3
  }
}

这仍然不太正确。你建议怎么做?

4

1 回答 1

1

您的 DataFrame(用于娱乐目的):

df= pd.DataFrame(
    {'north': [0.0, 0.0, 0.0],
     'B1_EMS_DH26': [1272.2, 1401.9, 1642.3],
     'tmax': [25, 26, 27],
     'wwr': [40, 40, 40],
     'ch': [2.5, 2.5, 2.5],
     'tmin': [24, 24, 24],
     'ach': [4.0, 4.0, 4.0]
     },
    index=['EP_P1203_000000000', 'EP_P1203_000000001', 'EP_P1203_000000002'],
    columns=['north', 'ch', 'wwr', 'ach', 'tmin', 'tmax', 'B1_EMS_DH26'])

这可能是最糟糕的方法,但它有效(我认为):

import re
import json

with open('whatever.json', 'w') as f:
    f.write('var results = [\n')
    for k,v in df.drop('B1_EMS_DH26', axis=1).T.to_dict().items():
        f.write("{name:"+json.dumps(k)+", "+re.sub(r'[{"\']', '', json.dumps(v))+',\n')
    f.write('];')

产生:

var results = [{
    name: "EP_P1203_000000001",
    ach: 4.0,
    north: 0.0,
    tmax: 26.0,
    tmin: 24.0,
    ch: 2.5,
    wwr: 40.0
  },
  {
    name: "EP_P1203_000000000",
    ach: 4.0,
    north: 0.0,
    tmax: 25.0,
    tmin: 24.0,
    ch: 2.5,
    wwr: 40.0
  },
  {
    name: "EP_P1203_000000002",
    ach: 4.0,
    north: 0.0,
    tmax: 27.0,
    tmin: 24.0,
    ch: 2.5,
    wwr: 40.0
  },
];

它将以我认为您正在寻找的结构输出一个文件。如果没有,请告诉我。我知道可怕的黑客攻击。具有高级 json 经验的人无疑知道更好的方法。

于 2017-02-22T19:04:52.913 回答