gpt4 book ai didi

python - 将系列转换为字典?

转载 作者:行者123 更新时间:2023-12-01 06:31:07 26 4
gpt4 key购买 nike

我有一个应用了 groupby 函数的数据集

data.groupby(by=['version','sentiment']).score.count()

输出是:

version  sentiment       
10.1.2 negative 3.0
positive 8.0
10.2.0 negative 1.0
10.4.2 negative 1.0
10.4.3 negative 1.0
10.4.6 positive 1.0
10.5.1 negative 1.0
10.5.2 positive 1.0
10.5.5 negative 2.0
11.0 negative 1.0
11.2 negative 3.0
positive 1.0
11.3.1 negative 1.0

不,我想将其转换为字典形式,输出应类似于:

{'10.1.2' : {
'positive' : 3,
'negative' : 8
},
'10.2.0' : {
}

最佳答案

我认为你只需要:

s.unstack().to_dict('index')
#.unstack(level = 0).to_dict()

s 是您的系列

data.groupby(by=['version','sentiment']).score.count().unstack().to_dict()
<小时/>

我使用 DataFrame 来解决您的问题

print(df)
i1 i2 col
0 10.1.2 negative 3.0
1 10.1.2 positive 8.0
2 10.2.0 negative 1.0
3 10.4.2 negative 1.0
4 10.4.3 negative 1.0
5 10.4.6 positive 1.0
6 10.5.1 negative 1.0
7 10.5.2 positive 1.0
8 10.5.5 negative 2.0
9 11.0 negative 1.0
10 11.2 negative 3.0
11 11.2 positive 1.0
12 11.3.1 negative 1.0


df.set_index(['i1','i2'])['col'].unstack().to_dict('index')
#{'10.1.2': {'negative': 3.0, 'positive': 8.0},
# '10.2.0': {'negative': 1.0, 'positive': nan},
# '10.4.2': {'negative': 1.0, 'positive': nan},
# '10.4.3': {'negative': 1.0, 'positive': nan},
# '10.4.6': {'negative': nan, 'positive': 1.0},
# '10.5.1': {'negative': 1.0, 'positive': nan},
# '10.5.2': {'negative': nan, 'positive': 1.0},
# '10.5.5': {'negative': 2.0, 'positive': nan},
# '11.0': {'negative': 1.0, 'positive': nan},
# '11.2': {'negative': 3.0, 'positive': 1.0},
# '11.3.1': {'negative': 1.0, 'positive': nan}}

关于python - 将系列转换为字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59915164/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com