Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas dataframe as field in django

I want to add pandas dataframe (or a numpy array) as a field in django model. Each model instance in django has a large size 2D array associated with it so I want to store it as numpy array or pandas dataframe.

please guide me how can I achieve it. I tried below but it doesn't work.

from django.db import models
import numpy    
class datafile(models.Model)
    filename = models.CharField(max_length=50)
    data = numpy.array((1000,1000))

I am reading data from excel file and setting it to data variable in views.py but after I save the model, the value for data doesn't get updated. regards, Rahul

like image 350
rahulchem Avatar asked Dec 30 '13 21:12

rahulchem


People also ask

Can I use pandas in Django?

In this tutorial, you will learn how to use pandas in Django data. And convert a query set of data into a Data frame. Like how you convert a CSV data file into a Data Frame. And perform the data science operation right away in Django Views.


1 Answers

You're likely gonna want to use a PickleField to store your numpy or Pandas dataframe. The PickleField will serialize the data into a text field for the database storage and convert it back upon retrieval.

from django.db import models
from picklefield.fields import PickledObjectField
import numpy

class DatafileModel(models.Model)
    data = PickledObjectField()

And then just create or manipulate your model instances with numpy or pandas objects:

datafile = DatafileModel()
datafile.data = numpy.array((1000,1000))
datafile.save()
like image 136
Kevin Stone Avatar answered Oct 17 '22 01:10

Kevin Stone