【发布时间】:2018-04-30 07:19:05
【问题描述】:
我在使用 Pandas 数据框的索引时遇到了一些问题。我要做的是从 JSON 文件加载数据,创建 Pandas 数据框,然后从该数据框中选择特定字段并将其发送到我的数据库。
以下是指向 JSON 文件中内容的链接,以便您可以看到实际存在的字段: https://pastebin.com/Bzatkg4L
import pandas as pd
from pandas.io import sql
import MySQLdb
from sqlalchemy import create_engine
# Open and read the text file where all the Tweets are
with open('US_tweets.json') as f:
tweets = f.readlines()
# Convert the list of Tweets into a structured dataframe
df = pd.DataFrame(tweets)
# Attributes needed should be here
df = df[['created_at', 'screen_name', 'id', 'country_code', 'full_name', 'lang', 'text']]
# To create connection and write table into MySQL
engine = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}"
.format(user="blah",
pw="blah",
db="blah"))
df.to_sql(con=engine, name='US_tweets_Table', if_exists='replace', flavor='mysql')
感谢您的帮助!
【问题讨论】:
-
您的原始数据框构造正确吗?具体来说,该数据框中存在哪些列?
-
@Evan 我认为您可能是对的,我将如何为数据框创建列?如果我错了,请纠正我,但似乎您是在说我应该在数据框中创建与 JSON 文件中的属性相关联的列。制作完这些列后,我可以将属性添加到列中吗?
-
发生错误是因为您尝试引用的列不在索引中:也就是说,它们不存在于您创建的第一个 df 中。它们存在于 JSON 文件中的对象中,但 pandas 不会为 JSON 中的每个对象创建列,仅针对最高级别。