[英]Python dictionary accumulative value to individual values
Now I have a Python dictionary my_dict:现在我有一个 Python 字典 my_dict:
level_1 ![]() |
level_2 ![]() |
level_3 ![]() |
level_4 ![]() |
level_5 ![]() |
---|---|---|---|---|
2 ![]() |
2 ![]() |
8 ![]() |
11 ![]() |
13 ![]() |
my_dict = {'level_1':2, 'level_2':2, 'level_3':8, 'level_4':11, 'level_5':13}
The value of the dictionary now is accumulative, I am wondering how to get the python dictionary with individual value:现在字典的值是累加的,我想知道如何获得具有个体值的 python 字典:
level_1 ![]() |
level_2 ![]() |
level_3 ![]() |
level_4 ![]() |
level_5 ![]() |
---|---|---|---|---|
2 ![]() |
0 ![]() |
6 ![]() |
3 ![]() |
2 ![]() |
Thanks in advance for any helps!在此先感谢您的帮助!
You can use pandas
for that, especially if your data grows for many columns:您可以为此使用
pandas
,尤其是当您的数据增长了很多列时:
df = pd.DataFrame(my_dict, index=[0])
df.diff(axis=1).fillna(df)
Without pandas, you may use a simple dict
comprehension:如果没有 pandas,您可以使用简单的
dict
理解:
{k: my_dict.get(f'level_{int(k[-1])}', 0) - \
my_dict.get(f'level_{int(k[-1]) - 1}', 0) \
for k in my_dict.keys()}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.