使用pandas读取JSON文件进行Python分析
我在使用Python编辑器加载一个JSON文件时遇到了一些问题,我想对里面的数据进行分析。
这个JSON文件在这个文件夹里:'C:\Users\Admin\JSON files\file1.JSON'
它包含了以下的推文数据(这只是其中一条记录,里面有好几百条):
{
"created": "Fri Mar 13 18:09:33 GMT 2014",
"description": "Tweeting the latest Playstation news!",
"favourites_count": 4514,
"followers": 235,
"following": 1345,
"geo_lat": null,
"geo_long": null,
"hashtags": "",
"id": 2144411414,
"is_retweet": false,
"is_truncated": false,
"lang": "en",
"location": "",
"media_urls": "",
"mentions": "",
"name": "Playstation News",
"original_text": null,
"reply_status_id": 0,
"reply_user_id": 0,
"retweet_count": 4514,
"retweet_id": 0,
"score": 0.0,
"screen_name": "SevenPS4",
"source": "<a href=\"http://twitterfeed.com\" rel=\"nofollow\">twitterfeed</a>",
"text": "tweetinfohere",
"timezone": "Amsterdam",
"url": null,
"urls": "http://bit.ly/1lcbBW6",
"user_created": "2013-05-19",
"user_id": 13313,
"utc_offset": 3600
}
我正在使用以下代码来测试这些数据:
import json
import pandas as pa
z = pa.read_json('C:\Users\Admin\JSON files\file1.JSON')
d = pa.DataFrame.from_dict([{k:v} for k,v in z.iteritems() if k in ["retweet_count", "user_id", "is_retweet"]])
print d.retweet_count.sum()
当我运行这段代码时,它成功读取了JSON文件,然后打印出了retweet_count的列表,像这样:
0, 4514
1, 300
2, 450
3, 139
等等
我有几个问题: 我该如何把所有的retweet_count/user_id值加起来,而不是像上面那样只列出它们?
然后我该如何把这个总和除以条目数来得到平均值?
我怎么能选择JSON数据的样本大小,而不是使用全部数据?(我以为是d.iloc[:10],但那不管用)
在JSON文件中的'is_retweet'字段里,能否统计一下true和false的数量?也就是说,我想知道在JSON文件中,有多少条推文被转发了,多少条没有。
提前谢谢你,我对这些还很陌生……
z.info()
的输出是:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 506 entries, 0 to 505
数据列(总共31列):
created 506 non-null object
description 506 non-null object
favourites_count 506 non-null int64
followers 506 non-null int64
following 506 non-null int64
geo_lat 10 non-null float64
geo_long 10 non-null float64
hashtags 506 non-null object
id 506 non-null int64
is_retweet 506 non-null bool
is_truncated 506 non-null bool
lang 506 non-null object
location 506 non-null object
media_urls 506 non-null object
mentions 506 non-null object
name 506 non-null object
original_text 172 non-null object
reply_status_id 506 non-null int64
reply_user_id 506 non-null int64
retweet_id 506 non-null int64
retweet_count 506 non-null int64
score 506 non-null int64
screen_name 506 non-null object
source 506 non-null object
status_count 506 non-null int64
text 506 non-null object
timezone 415 non-null object
url 273 non-null object
urls 506 non-null object
user_created 506 non-null object
user_id 506 non-null int64
utc_offset 506 non-null int64
数据类型:bool(2), float64(2), int64(11), object(16)
为什么当我运行d.info()时,retweet_count和user_id显示为对象类型?
1 个回答
d.retweet_count
是一个字典列表,用来存储你的 retweet_counts
对吧?
那么要计算总和的话:
keys = d.retweet_count.keys()
sum = 0
for items in keys:
sum+=d.retweet_count[items]
要计算平均值的话:
avg = sum/len(keys)
现在要得到样本大小,只需要把 keys
除开:
sample_keys = keys[0:10]
这样就能得到平均数了
for items in sample_keys:
sum+=d.retweet_count[items]
avg = sum/len(sample_keys)