python: разбивка по возрастной группе по среднему количеству друзей - PullRequest
0 голосов
/ 16 января 2019

у меня есть датафрейм с 4 атрибутами, это видно как удар.

enter image description here

что я хотел сделать, это взять имя и возраст человека и подсчитать количество друзей, которые у него есть. затем из двух человек одного возраста с разными именами, берите среднее число друзей для этой возрастной группы. окончательно разделите возрастной диапазон на возрастную группу и затем возьмите среднее Вот как я пытался.

#loc the attribute or features of interest
friends = df.iloc[:,3]
ages = df.iloc[:,2]

# default of dictionary with age as key and value as a list of friends 
dictionary_age_friends = defaultdict(list)

# populating the dictionary with key age and values friend
for i,j in zip(ages,friends):
    dictionary_age_friends[i].append(j)
print("first dict")
print(dictionary_age_friends)

#second dictionary, the same age is collected and the number of friends is added 
set_dict ={}
for x in dictionary_age_friends:
    list_friends =[]
    for y in dictionary_age_friends[x]:
        list_friends.append(y)
    set_list_len = len(list_friends) # assign a friend with a number 1
    set_dict[x] = set_list_len
print(set_dict)

# set_dict ={}
# for x in dictionary_age_friends:
#     print("inside the loop")
#     lis_1 =[]
#     for y in dictionary_age_friends[x]:
#         lis_1.append(y)
#         set_list = lis_1
#         set_list = [1 for x in set_list] # assign a friend with a number 1
#         set_dict[x] = sum(set_list)

# a dictionary that assign the age range into age-groups
second_dict = defaultdict(list)
for i,j in set_dict.items(): 
    if i in range(16,20):           
        i = 'teens_youthAdult'
        second_dict[i].append(j)
    elif i in range(20,40):       
        i ="Adult"
        second_dict[i].append(j)
    elif i in  range(40,60):        
        i ="MiddleAge"
        second_dict[i].append(j)
    elif i in range(60,72):       
        i = "old"
        second_dict[i].append(j)
print(second_dict)
print("final dict stared")
new_dic ={}

for key,value in second_dict.items():
    if key == 'teens_youthAdult':
        new_dic[key] = round((sum(value)/len(value)),2)
    elif key =='Adult':
        new_dic[key] = round((sum(value)/len(value)),2)
    elif key =='MiddleAge' :
        new_dic[key] = round((sum(value)/len(value)),2)
    else:
        new_dic[key] = round((sum(value)/len(value)),2)
new_dic
end_time = datetime.datetime.now()


print(end_time-start_time)


print(new_dic)

некоторые отзывы, которые я получил: 1, нет необходимости составлять список, если вы хотите просто посчитать количество друзей. 2, два человека одного возраста, 18 лет. У одного 4 друга, у другого 3. текущий код заключает, что в среднем 7 друзей. 3, код не является правильным и оптимальным.

какие-либо предложения или помощь? спасибо за все предложения или помощь?

1 Ответ

0 голосов
/ 17 января 2019

Я не понял названия атрибутов, и вы не упомянули, по каким возрастным группам вам нужно разделить ваши данные. В своем ответе я буду относиться к данным, как если бы атрибуты были:

index, name, age, friend

Чтобы найти количество друзей по имени, я бы предложил вам использовать groupby .

ввод:

groups = df.groupby([df.iloc[:,0],df.iloc[:,1]]) # grouping by name(0), age(1)
amount_of_friends_df = groups.size() # gathering amount of friends for a person
print(amount_of_friends_df)

выход:

name  age
EUNK  25     1
FBFM  26     1
MYYD  30     1
OBBF  28     2
RJCW  25     1
RQTI  21     1
VLIP  16     1
ZCWQ  18     1
ZMQE  27     1

Чтобы узнать количество друзей по возрасту, вы также можете использовать группы

ввод:

groups = df.groupby([df.iloc[:,1]]) # groups by age(1)
age_friends = groups.size() 
age_friends=age_friends.reset_index()
age_friends.columns=(['age','amount_of_friends'])
print(age_friends)

выход:

    age  amount_of_friends
0   16                  1
1   18                  1
2   21                  1
3   25                  2
4   26                  1
5   27                  1
6   28                  2
7   30                  1

Чтобы рассчитать среднее количество друзей в возрастной группе, вы можете использовать категории и groupby.

ввод:

mean_by_age_group_df = age_friends.groupby(pd.cut(age_friends.age,[20,40,60,72]))\
.agg({'amount_of_friends':'mean'})
print(mean_by_age_group_df)

pd.cut возвращает ряды, которые мы используем для группировки данных. Затем мы используем функцию agg для агрегирования групп в фрейме данных.

выход:

          amount_of_friends
age                        
(20, 40]           1.333333
(40, 60]                NaN
(60, 72]                NaN
...