URL 给出了 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 的直观处理使其成为满足您需求的有吸引力的捷径。
关于python - 从url读取csv并通过pandas将其推送到数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40047291/