所以我有一个列表列表,其中每个子列表的第7个索引包含我感兴趣的平均值,但是,这些数字必须根据它们的类型进行平均。在子列表的第11个索引中可以找到要匹配的类型。你知道吗
下面是我写的一些代码。在这个例子中
# Open the csv file
opened_file = open('AppleStore.csv')
from csv import reader
read_file = reader(opened_file)
# Store the data as a list or arrays
apps_data = list(read_file)
# idx_num = index number of interest
# list_doc = the list of lists
# row_start = 1
def extract(idx_num,list_doc,row_start=1):
a_list = []
for row in list_doc[row_start:]:
var = row[idx_num]
a_list.append(var)
return a_list
# Use the extract function to get an array
a_list = extract(11, apps_data, 0)
# Find unique elements
a_list_set = set(a_list)
# Create a dictionary with initial values at [0,0]
dic = dict.fromkeys(a_list_set,[0,0])
print(dic)
# Works as intended
#{'Weather': [0, 0], 'Sports': [0, 0], 'Productivity': [0, 0], 'Games': [0, #0], 'News': [0, 0], 'Finance': [0, 0], 'Education': [0, 0], #'Entertainment': [0, 0], 'Health & Fitness': [0, 0], 'Business': [0, 0], #'Social Networking': [0, 0], 'prime_genre': [0, 0], 'Photo & Video': [0, #0], 'Navigation': [0, 0], 'Music': [0, 0], 'Medical': [0, 0], 'Travel': #[0, 0], 'Reference': [0, 0], 'Shopping': [0, 0], 'Utilities': [0, 0], #'Food & Drink': [0, 0], 'Lifestyle': [0, 0], 'Catalogs': [0, 0], 'Book': #[0, 0]}
for row in apps_data[1:]:
price = float(row[4])
genre = row[11]
# Here is the issue:
# I thought that this would allow for the genre instance to be matched to the appropriate key and then I could append my values.
if genre in dic.keys():
dic[genre][0] += 1
dic[genre][1] += (price)
else:
dic[genre][0] = 1
dic[genre][1] = price
print(dic)
## From here I would extract the array contents of the dictionary
for genre in a_list_set:
print(str(genre) + " mean price:" + str(round(dic[genre][1]/dic[genre][0], 2)))
我得到了这个。你知道吗
{'Weather': [7197, 12423.58999999945], 'Sports': [7197, 12423.58999999945], 'Productivity': [7197, 12423.58999999945], 'Games': [7197, 12423.58999999945], 'News': [7197, 12423.58999999945], 'Finance': [7197, 12423.58999999945], 'Education': [7197, 12423.58999999945], 'Entertainment': [7197, 12423.58999999945], 'Health & Fitness': [7197, 12423.58999999945], 'Business': [7197, 12423.58999999945], 'Social Networking': [7197, 12423.58999999945], 'prime_genre': [7197, 12423.58999999945], 'Photo & Video': [7197, 12423.58999999945], 'Navigation': [7197, 12423.58999999945], 'Music': [7197, 12423.58999999945], 'Medical': [7197, 12423.58999999945], 'Travel': [7197, 12423.58999999945], 'Reference': [7197, 12423.58999999945], 'Shopping': [7197, 12423.58999999945], 'Utilities': [7197, 12423.58999999945], 'Food & Drink': [7197, 12423.58999999945], 'Lifestyle': [7197, 12423.58999999945], 'Catalogs': [7197, 12423.58999999945],'Book': [7197, 12423.58999999945]}
我们可以用
itertools.groupby
来实现这一点;首先,我们从我们的数据中提取相关的“列”,构成每行的第7和第11个值,放入subset
,也按第11个值排序。你知道吗然后,我们使用
groupby
将子集划分为多个组,每个组的成员都有相同的第2个元素(原来的第11个元素)。然后我们可以使用dict
理解来获得每个组成员的第一个元素的平均值。你知道吗一些示例数据:
结果是:
相关问题 更多 >
编程相关推荐