Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

Pandas/Django - Cannot convert csv saved as filefield into dataframe

I'm building a database that stores csv files and presents them when a user selects the csv he/she wants to visualize. The problem is, whenever I open the csv file from the database the resulting dataframe is garbage

models.py

class Csv(models.Model):
    file_name = models.FileField(upload_to='csvs', max_length = 100)
    public = models.BooleanField(default = False)
    user = models.ForeignKey(User, on_delete = models.CASCADE, null = True)
    name = models.CharField(max_length = 100)
    library = models.CharField(max_length = 100, null = True)

    def __str__(self):
        return "File id: {}".format(self.id)

views.py

def test(request):
    csv = Csv.objects.get(id = 5)
    df = pd.DataFrame(csv.file_name)
    print(df.head())
    return render(request, 'mainproj/test.html', {'df' : df.dtypes})

Test_Data.csv


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Turns out the following line of code is what I needed

dataframe = pd.read_csv(io.StringIO(file_obj.read().decode('utf-8')), delimiter=',')


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...