[英]How can I load into a pandas DataFrame tweets from a json file?
我正在嘗試使用以下代碼讀取以 json 格式保存的 Twitter 數據:
import json
with open(file, 'r') as f:
line = f.readline()
tweet = json.loads(line)
df1 = pd.DataFrame(tweet)
這段代碼只讀取一條推文並且它有效,但是當我嘗試通過以下方式讀取所有文件時:
with open(file, 'r') as f:
for line in f:
tweet = json.loads(line)
我收到一個錯誤:
JSONDecodeError: Expecting value: line 2 column 1 (char 1)
我應該更改什么才能正確讀取此文件?
我的主要任務是找到這些推文的創建日期,我使用以下過濾器找到了它(我只使用了一條在開始時有效的推文):
df2 = df[["user"]]
df3 = df2.loc[['created_at']]
df3
有沒有比 DataFrames 更好的方法來處理這些數據?
一種更簡潔的方式來讀取(所有)你的 JSON 文件給我看起來像
import pandas as pd
df = pd.read_json("python.json", orient = 'records', lines = True)
然后,您可以對df
應用轉換,以便從您感興趣的列中獲取數據。
你可以這樣做:
import pandas as pd
#results is the JSON tweet data.
#Define the columns you want to extract
resultFrame = pd.DataFrame(columns=["username","created_at","tweet"])
print len(results)
for i in range(len(results)):
resultFrame.loc[i,"username"] = results[i].user.screen_name
resultFrame.loc[i, "created_at"] = results[i].created_at
resultFrame.loc[i, "tweet"] = results[i].text
print resultFrame.head()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.