我需要从 CSV 文件创建一个表。
我想我可以用不同的库来做到这一点,但在这种情况下,我选择使用pandas,因为在不久的将来我会更需要它来进行一些数据分析。
我有一个脚本,但出现此错误:
Traceback (most recent call last):
File "/home/gonzales/Escritorio/virtual_envs/stickers_gallito_env/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 3078, in get_loc
return self._engine.get_loc(key)
File "pandas/_libs/index.pyx", line 140, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/index.pyx", line 162, in pandas._libs.index.IndexEngine.get_loc
File "pandas/_libs/hashtable_class_helper.pxi", line 958, in pandas._libs.hashtable.Int64HashTable.get_item
File "pandas/_libs/hashtable_class_helper.pxi", line 964, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 1867
Dropbox 中的数据:
https://www.dropbox.com/s/o3iga509qi8suu9/ubigeo-peru-2018-12-25.csv?dl=0
脚本:
import pandas as pd
import csv
from shop.models import Peru
from django.core.management.base import BaseCommand
tmp_data=pd.read_csv('static/data/ubigeo-peru-2018-12-25.csv',sep=',', encoding="utf-8")
class Command(BaseCommand):
def handle(self, **options):
products = [
Peru(
departamento=tmp_data.ix[row]['departamento'],
provincia=tmp_data.ix[row]['provincia'],
distrito=tmp_data.ix[row]['distrito'],
)
for row in tmp_data['id']
]
Peru.objects.bulk_create(products)
模型.py
class Peru(models.Model):
departamento = models.CharField(max_length=100, blank=False)
provincia = models.CharField(max_length=100, blank=False)
distrito = models.CharField(max_length=100, blank=False)
def __str__(self):
return self.departamento
饮歌长啸
相关分类