如何将pandas.DataFrame转换为gviz_api.DataTable

时间:2012-11-29 16:29:59

标签: api pandas google-visualization

我有一个pandas.DataFrame对象,我想将其转换为gviz_api.DataTable,然后我会在谷歌图表中使用它。

有一种简单的方法吗?

2 个答案:

答案 0 :(得分:0)

我不知道将pandas数据帧强制转换为gviz数据表的任何简单方法。

我是这样做的: -

from gviz_data_table import Table   # using https://bitbucket.org/charlie_x/gviz-data-table though you should probably use the official google one.
import numpy as np
import pandas as pd

df = pd.DataFrame({
    "time" : [1,2,3,4,5],
    "temp" : np.random.rand(5)
})

table = Table()
table.add_column('temp', float, 'Temp')
table.add_column('time', float, 'Time')

for row in df.iterrows():
    table.append(row[1].tolist())

table.rows

[OrderedDict([('temp', <gviz_data_table.cell.Cell object at 0x104a64aa0>), ('time', <gviz_data_table.cell.Cell object at 0x104a64a50>)]),
 OrderedDict([('temp', <gviz_data_table.cell.Cell object at 0x104a64af0>), ('time', <gviz_data_table.cell.Cell object at 0x104a64b40>)]),
 OrderedDict([('temp', <gviz_data_table.cell.Cell object at 0x104a64b90>), ('time', <gviz_data_table.cell.Cell object at 0x104a64be0>)]),
 OrderedDict([('temp', <gviz_data_table.cell.Cell object at 0x104a64c30>), ('time', <gviz_data_table.cell.Cell object at 0x104a64c80>)]),
 OrderedDict([('temp', <gviz_data_table.cell.Cell object at 0x104a64cd0>), ('time', <gviz_data_table.cell.Cell object at 0x104a64d20>)])]

答案 1 :(得分:0)

作为使用iterrows和list的替代方法,您可以使用.values将数据帧作为numpy对象(数组数组 - 每行一个)

完成整个过程并将其转换为GViz表

  • 设置说明
  • 使用gviz_api的LoadData()方法加载值。

代码示例

#set up Google Table w/ the description
gpa_desc=[("grade_date", "date", "Date" ),
          ("gpa", "number", "GPA")]
gpa_data_table=gviz_api.DataTable(gpa_desc)

#your df as a numpy object
gpa_values=df_gpa.values

#populate the table with your data 
gpa_data_table.LoadData(gpa_values)

#convert to json to pass to the view
gpa_json=gpa_data_table.ToJSon()