【问题标题】:Error when writing data to postgresql using pandas dataframe使用 pandas 数据框将数据写入 postgresql 时出错
【发布时间】:2019-07-03 12:19:13
【问题描述】:

我正在尝试将 csv 列值保存在 postgres 数据库中。我使用熊猫来获取 csv 列值。但是每当我尝试将列值保存在我的数据库表列中时,都会出现错误。 这是我的代码:

import pandas as pd

file = request.files['csvFile[]']
print('file.filename: ',file.filename)
jh = pd.read_csv(file, dtype={"name": str})
names = jh.name
print(names)

user = GenderInfo(name=jh.name)
db.session.add(user)
db.session.commit()

这是打印后的结果

names=jh.name

enter image description here

我经常收到错误

'Series' 对象是可变的,因此它们不能被散列

我在谷歌上搜索了这个问题,但我无法解决这个问题。如果有任何关于此问题的帮助,或者如果有任何其他替代方法可以将 csv 列数据保存在数据库列中,我们将不胜感激。

【问题讨论】:

  • 您能否发布完整的回溯,我认为这与GenderInfo 构造函数如何解析jh.name 系列有关。
  • 查看已编辑的问题,我添加了一张图片。 "jh.name" 打印 csv 文件中的所有性别名称
  • 感谢您更新帖子。我实际上在寻找的是打印到控制台的完整 python 回溯。它应该看起来像这样:Traceback (most recent call last): File "C:/repo/global/panda_test.py", line 8, in <module> print(hash(df.name)) File "C:\Program Files\Python36\lib\site-packages\pandas\core\generic.py", line 1045, in __hash__ ' hashed'.format(self.__class__.__name__)) TypeError: 'Series' objects are mutable, thus they cannot be hashed
  • 我再次编辑了我的帖子。查看新附上的图片
  • 哦,我明白了,try except 块正在抑制完整的回溯。您可以在except 块的末尾添加raise 语句并在问题中发布回溯文本吗?

标签: python pandas postgresql csv


【解决方案1】:

完成了! 这是代码

def upload_cs():
    file = request.files['excelFile[]']
    stream = io.StringIO(file.stream.read().decode("UTF8"), newline=None)
    csv_input = csv.DictReader(stream)

    # Validate and deserialize input
    data, errors = genderInfoDto.load(file)

    print('data: ', data)


    for row in csv_input:
        jh = GenderInfo.query.filter_by(name=row['name']).first()
        print('GenderInfo: ', jh)
        if jh:
            return Response(json.dumps({'status': 'failed', 'message': 'gender already exists.'}), status=200,
                            mimetype='application/json')
        print(row['name'])
        user = GenderInfo(row['name'])
        db.session.add(user)
        db.session.commit()
    result = genderInfoDto.dump(user).data
    stream.seek(0)

    return Response(json.dumps({'status': 'success', 'message': 'file upload successfully  .', 'data': result}),
                    status=200, mimetype='application/json')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-21
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 2014-01-21
    • 2018-04-20
    相关资源
    最近更新 更多