V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
qazwsxkevin
V2EX  ›  Python

pandas 读入数据后的 DataFrame,再写入 mysql,如何以 DF 的第一行内容作为 mysql 的字段名?

  •  
  •   qazwsxkevin · 2019-05-18 00:38:59 +08:00 · 2085 次点击
    这是一个创建于 1798 天前的主题,其中的信息可能已经有所发展或是发生改变。
    ```
    PageDF = PageDF.append(pd.read_html(readStr)[4], ignore_index=True)
    print(PageDF)
    engine = create_engine('mysql+pymysql://root:[email protected]:3306/test?charset=utf8')
    PageDF.to_sql(Testtable,engine,index=False)
    ```

    Print(PageDF)

    ```
    0 1 2 3
    0 序号 物品名称 重量 柜号
    1 1 西瓜 20 14
    2 2 芝麻 20 11
    3 3 玉米 20 11
    4 4 茄子 20 9
    ```

    Navicat 看到 Testtable 是这样的:
    ```
    +------+-------+------------+------+------+
    |0 | 0 | 1 | 2 | 3 |
    +------+-------+------------+------+------+
    |0 | 序号 | 物品名称 | 重量 | 柜号 |
    |1 | 1 | 西瓜 | 20 | 14 |
    |2 | 2 | 芝麻 | 20 | 11 |
    |3 | 3 | 玉米 | 20 | 11 |
    |4 | 4 | 茄子 | 20 | 9 |
    ```

    但我想写进去的时候是这样子的,看了 to_sql 的英文文档,试了 index_lable=0 那些参数,始终弄不成下面这个样子的写入状态:

    ```
    +------+-------+------------+------+------+
    |0 | 序号 | 物品名称 | 重量 | 柜号 |
    +------+-------+------------+------+------+
    |1 | 1 | 西瓜 | 20 | 14 |
    |2 | 2 | 芝麻 | 20 | 11 |
    |3 | 3 | 玉米 | 20 | 11 |
    |4 | 4 | 茄子 | 20 | 9 |
    ```

    请问正确的 to_sql 写入方式应该是怎么做的?

    感谢各位热心解答~~~
    3 条回复    2019-05-18 13:48:57 +08:00
    binux
        1
    binux  
       2019-05-18 02:40:26 +08:00 via iPhone
    你先把 pageDF 的 columns 整对了
    给 read_Html 加参数
    或者你手动 assign columns
    qazwsxkevin
        2
    qazwsxkevin  
    OP
       2019-05-18 13:16:42 +08:00
    @binux 感谢感谢,看来是没有自带方法这么做,发帖前也查过文档,这里高手多,是想试着问问也许有妖招吧。。。^_^
    现在老老实实组装 MySQL 语句 ing...
    binux
        3
    binux  
       2019-05-18 13:48:57 +08:00
    @qazwsxkevin #2 怎么就没有了?

    > 给 read_Html 加参数
    ```
    header : int or list-like or None, optional
    The row (or list of rows for a MultiIndex) to use to make the columns headers.
    ```

    > 或者你手动 assign columns
    ```
    pageDF.columns = pageDF.iloc[0]
    ```

    难道我要喂你嘴里你才会吃吗?你能不能花 30 分钟把入门文档给看了?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5464 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 03:03 · PVG 11:03 · LAX 20:03 · JFK 23:03
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.