python - 熊猫数据框返回列标题链接到每行的数据值
问题描述
我正在使用 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
我尝试使用zip
并iterrows
使用以下代码:
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
但我需要为每行创建一个插入语句。谢谢
解决方案
@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'}]
推荐阅读
- spring-boot - Swagger codegen Maven 插件在 SpringBoot 中没有生成正确的 dateFormat java.time.LocalDate
- c++ - 如果 sizeof(T) 大于 std::deque 中的块大小怎么办
? - spartacus-storefront - 将默认页面更改为登录
- javascript - 我刚刚在导航栏中添加了汉堡包按钮,但它现在不起作用?
- mysql - 数据库上的 i/o 如何与查询类型相关
- linux - cut -f 多个参数
- c# - 如何每 n 分钟/小时/天使用 Hangfire 运行后台作业
- listview - 秒表时间跨度的列表视图 - 如何在 UI 中继续计时器
- typescript - 解决 Vue 3 可组合项中的循环依赖关系
- mongodb - 如何在 MongoDB 上查询 NOT LIKE 数组中的任何字符串?