该网址提供了csv格式的数据。我正在尝试获取数据并将其推送到数据库中。但是,我无法读取数据,因为它仅打印文件的标头,而不完整地显示csv数据。会有更好的选择吗?
#!/usr/bin/python3
import pandas as pd
data = pd.read_csv("some-url") //URL not provided due to security restrictions.
for row in data:
print(row)
最佳答案
您可以遍历df.to_dict(orient="records")
的结果:
data = pd.read_csv("some-url")
for row in data.to_dict(orient="records"):
# For each loop, `row` will be filled with a key:value dict where each
# key takes the value of the column name.
# Use this dict to create a record for your db insert, eg as raw SQL or
# to create an instance for an ORM like SQLAlchemy.
尽管我正在使用Pandas合并来自多个源的数据,而不是仅仅读取文件,但我还是对SQLAlchemy插入的数据进行预格式化进行了类似的操作。
旁注:如果没有Pandas,只需遍历文件行,还有许多其他方法可以做到这一点。但是,Pandas对CSV的直观处理使其成为执行所需操作的极具吸引力的捷径。