[英]How to import JSON file into Pandas Dataframe
我一直在尋找將數據加載到Pandas的幾種不同方法。 如果有人對這些例外有任何建議,將不勝感激! 在某些示例中,文件名在tweet_json.txt和tweet_json.json之間更改,因為我嘗試了不同的方法。
with open('tweet_json.json', 'r') as f:
data = json.load(f)
df_3 = pd.DataFrame(data)
結果為: JSONDecodeError: Extra data: line 2 column 1 (char 3974)
df_3 = pd.read_json('tweet_json.json', lines = True)
結果: ValueError: Unexpected character found when decoding object value
with open('tweet_json.txt') as file:
status = []
for line in file:
data = json.loads(line)
df_3 = pd.Dataframe(data)
結果為: JSONDecodeError: Expecting ',' delimiter: line 1 column 1626 (char 1625)
我僅有的一次獲得遠程成功的方法是使用json.dumps(),但這只是將其加載到沒有任何解析的單列數據幀中,而且json看起來像一個多級字典,我不知道該如何分離它:
data = []
with open('tweet_json.json') as f:
for line in f:
data.append(json.dumps(line))
df_3 = pd.DataFrame(data)
您可以使用json_normalize或read_json將json文件讀入數據幀。
如果您具有嵌套的json結構,則還可以使用from_records函數
這就是我解決問題的方法。 我沒有定義要導入和使用地圖的列。 我仍然不知道如何將整個JSON導入df,但這確實滿足了我的需要。
tweets_data = []
tweet_file = open('tweet_json.txt', "r")
for line in tweet_file:
try:
tweet = json.loads(line)
tweets_data.append(tweet)
except:
continue
tweet_file.close()
tweet_info = pd.DataFrame()
tweet_info['id'] = list(map(lambda tweet: tweet['id'], tweets_data))
tweet_info['retweet_count'] = list(map(lambda tweet: tweet['retweet_count'], tweets_data))
tweet_info['favorite_count'] = list(map(lambda tweet: tweet['favorite_count'], tweets_data))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.