我有四个列表,它们的长度约为200,000。第一个列表的小时值介于1到24之间,下面是一个示例
Hour_list = [1,2,2,2,5,5,7,5,12,18,24,.....]
avg_occupancy = [0,5,9,5,13,24,56,23,.....]
avg_absences = [0,4,5,7,8,6,8,3,2,1.....]
Room_config= ['config_a001', 'configa002', 'configa003', 'configa004', 'configa005'.........]
我需要为每个小时创建24个列表,分别是list_hour1,List_Hour2等,然后基于它们过滤其他三个列表,例如,List_Hour2应该包含数字2,而avg_ocupancy_hour_2应该包含所有具有以下索引的项目:对应于第一个列表中数字2的索引,这意味着avg_ocupancy_hour_2 = [5,9,5,......],avg_absences_2 = [4,5,7,....],Room_config = [ 'configa002','configa003','configa004','configa005'.........]
我认为Zip会很好,但不确定如何在这种情况下使用它
答案 0 :(得分:3)
是的,这就像..正是数据帧为何物一样。
Hour_list = [1,2,2,2]
avg_occupancy = [0,5,9,5]
avg_absences = [0,4,5,7]
Room_config= ['config_a001', 'configa002', 'configa003', 'configa004']
将它们放入大熊猫中
import pandas as pd
data = pd.DataFrame(dict(Hour_list = Hour_list, avg_occupancy = avg_occupancy, avg_absences = avg_absences, Room_config = Room_config))
分组整理:
hour_groups = data.groupby('Hour_list')
现在您可以执行任何操作-您可以计算摘要统计信息,也可以只遍历所有时间:
for hour, hour_data in hour_groups:
do_stuff(hour_data)
对于您的后续问题,您可以采取以下手段并计数:
mean_data = hour_groups[['avg_occupancy', 'avg_absences']].agg('mean')
mean_data['count'] = hour_groups['avg_occupancy'].count()
然后,您可以使用.loc
和逻辑测试来选择索引为9(即小时9)的任何行。
mean_data.loc[mean_data.index == 9, :]
, :
部分告诉熊猫返回符合mean_data.index == 9
测试的任何行的所有列。
答案 1 :(得分:1)
使用zip
和defaultdict
(以及清洁等级):
从集合中导入defaultdict
hour_list = [1,2,2,2,5,5,7,5]
avg_occupancy = [0,5,9,5,13,24,56,23]
avg_absences = [0,4,5,7,8,6,8,3]
room_config = ['configa001', 'configa002', 'configa003', 'configa004',
'configa005', 'configa006', 'configa007', 'configa008']
class Tracker:
def __init__(self):
self.avg_occupancy = defaultdict(list)
self.avg_absences = defaultdict(list)
self.room_config = defaultdict(list)
def add(self, h, ao, aa, rc):
self.avg_occupancy[h].append(ao)
self.avg_absences[h].append(aa)
self.room_config[h].append(rc)
# Optional, of course
def __repr__(self):
import json
return json.dumps(vars(self), indent=4)
t = Tracker()
for row in zip(hour_list, avg_occupancy, avg_absences, room_config):
t.add(*row)
print(t)
产生:
{ "avg_occupancy": { "1": [0], "2": [5, 9, 5], "5": [13, 24, 23], "7": [56] }, "avg_absences": { "1": [0], "2": [4, 5, 7], "5": [8, 6, 3], "7": [8] }, "room_config": { "1": ["configa001"], "2": ["configa002", "configa003", "configa004"], "5": ["configa005", "configa006", "configa008"], "7": ["configa007"] } }
答案 2 :(得分:1)
import pandas as pd
import numpy as np
hours = np.arange(1, 25)
data = {'hours': [hours[np.random.randint(low=0, high=24)] for i in np.arange(1000)],
'occupancy': np.random.randint(low=0, high=100, size=1000),
'absences' : np.random.randint(low=0, high=10, size= 1000)
}
df = pd.DataFrame(data=data)
# Extract data for hour == 7
df[df['hours'] == 7]