简体   繁体   English

初始化列表的dict并在Python中更新其值

[英]Initialize dict of list and update its values in Python

I have a data frame below: 我有一个数据框如下:

user | speed
------------
Anna | 1.0
Bell | 1.2
Anna | 1.3
Chad | 1.5
Bell | 1.4
Anna | 1.1

that I want to use a dictionary to keep record of the number of encounters for each user and update his/her speed when I loop through the data frame. 我希望使用字典来记录每个用户的遭遇次数,并在循环数据框时更新他/她的速度。

For instance, the first time we see "Anna" the dictionary is: 例如,我们第一次看到“Anna”字典是:

{"Anna": [1, 1.0]}

and the second time we see "Anna" it becomes: 我们第二次看到“安娜”它变成了:

{"Anna": [2, 1.3], "Bell": [1, 1.2]}

in the end the dictionary should be: 最后字典应该是:

{"Anna": [3, 1.1], "Bell": [2, 1.4], "Chad": [1, 1.5]}

The counting part is easy: 计数部分很简单:

>>> import pandas as pd
>>> record = pd.DataFrame({"user": ("Anna", "Bell", "Anna", "Chad", "Bell", "Anna"), "speed": (1.0, 1.2, 1.3, 1.5, 1.4, 1.1)})
>>> record
   speed  user
0    1.0  Anna
1    1.2  Bell
2    1.3  Anna
3    1.5  Chad
4    1.4  Bell
5    1.1  Anna
>>> encounter = {}
>>> for i in record['user']:
...   encounter[i] = encounter.get(i, 0) + 1
...
>>> encounter
{'Anna': 3, 'Bell': 2, 'Chad': 1}

but what's a good way to create an empty dictionary of list and update the second value? 但是创建列表空字典并更新第二个值的好方法是什么? Thanks! 谢谢!

I believe this is what you want in two lines. 我相信这是你想要的两行。

import pandas as pd

record = pd.DataFrame({
  "user": ("Anna", "Bell", "Anna", "Chad", "Bell", "Anna"), 
  "speed": (1.0, 1.2, 1.3, 1.5, 1.4, 1.1)
})

encounter = {}
for name, value in zip(record["user"], record["speed"]):
  encounter[name] = [encounter.get(name, [0])[0] + 1, value]
  1. The zip method let you loop through the names and speeds simultaneously. zip方法可让您同时循环显示名称和速度。
  2. The get method try gets the record if it exists, else return a list [0] . get方法尝试获取记录(如果存在),否则返回列表[0]
  3. The second [0] takes the first element of the list, which is the counter. 第二个[0]获取列表的第一个元素,即计数器。
  4. Finally it combines with the new value, becomes a new list, and assigned to encounter[name] . 最后它与新值组合,成为一个新列表,并分配给encounter[name]

Using collections.Counter 使用collections.Counter

Ex: 例如:

import pandas as pd
from decimal import Decimal
from collections import Counter

record = pd.DataFrame({"user": ("Anna", "Bell", "Anna", "Chad", "Bell", "Anna"), "speed": (1.0, 1.2, 1.3, 1.5, 1.4, 1.1)})

encounter = {}
for k,v in Counter(record["user"].tolist()).items():
    encounter[k] = [v, (record[record["user"] == k]["speed"].iloc[-1]).round(1).astype(Decimal)]

print(encounter)

Output: 输出:

{'Anna': [3, 1.1], 'Chad': [1, 1.5], 'Bell': [2, 1.4]}

go with pandorable , pandorable

my_dictionary={}
for k, v in df.groupby('user'):
    my_dictionary[k]=[len(v),v.iloc[-1]['speed']]
print(my_dictionary)
{'Anna': [3, 1.1], 'Bell': [2, 1.4], 'Chad': [1, 1.5]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM