首页 > 解决方案 > 熊猫数据框返回列标题链接到每行的数据值

问题描述

我正在使用 pandas 读取任何 CSV 文件,然后将行插入数据库。我将使用 SQLAlchemy 来做这件事。

我不知道标题名称或大小,所以它必须是动态的。假设数据库规则将确保数据的有效性。

我正在尝试将列标题映射到每个数据值。请参阅下面我当前的数据框:

  Example 1 Example 2 Example 3 Example 4
        Cat       Dog     Mouse     Horse
        Cow       Ant       Pig  Elephant

这是我想要的输出列表:

Example 1=Cat, Example 2=Dog, Example 3=Mouse, Example 4=Horse
Example 1=Cow, Example 2=Ant, Example 3=Pig, Example 4=Elephant

我尝试使用zipiterrows使用以下代码:

    for index, data in df.iterrows():
        mylist.append(data.values)

    myzip = zip(columns, mylist)

    for z in myzip:
        print(z)

但这会为每个多个值生成一个列标题,如下所示:

('Example 1', array(['Cat', 'Dog', 'Mouse', 'Horse'], dtype=object))
('Example 2', array(['Cow', 'Ant', 'Pig', 'Elephant'], dtype=object))

任何帮助将不胜感激,因为不确定我需要使用什么功能。我知道,to_sql但我需要为每行创建一个插入语句。谢谢

标签: pythonpandasdataframeheadertuples

解决方案


@giser_yugang 找到了理想的解决方案。Pandas具有转换数据帧并返回字典的内置方法DataFrame.to_dict(orient='dict'),其中可以使用参数自定义键值对orient
“东方”中的“记录”给出了你想要的结果。

所以你的数据框:

数据框

使用后:

df.to_dict(orient='records')

给出:

[{'Example 1': 'Cat',
  'Example 2': 'Dog',
  'Example 3': 'Mouse',
  'Example 4': 'Horse'},
 {'Example 1': 'Cow',
  'Example 2': 'Ant',
  'Example 3': 'Pig',
  'Example 4': 'Elephant'}]

推荐阅读