gpt4 book ai didi

python - 连接重复值/行的问题

转载 作者:行者123 更新时间:2023-11-28 22:31:26 24 4
gpt4 key购买 nike

Python 新手,似乎无法理解如何进行。在使用 bin 并编辑我的数据框后,我能够想出这个:

    Continents  % Renewable Country
0 Asia (15.753, 29.227] China
1 North America (2.212, 15.753] United States
2 Asia (2.212, 15.753] Japan
3 Europe (2.212, 15.753] United Kingdom
4 Europe (15.753, 29.227] Russian Federation
5 North America (56.174, 69.648] Canada
6 Europe (15.753, 29.227] Germany
7 Asia (2.212, 15.753] India
8 Europe (15.753, 29.227] France
9 Asia (2.212, 15.753] South Korea
10 Europe (29.227, 42.701] Italy
11 Europe (29.227, 42.701] Spain
12 Asia (2.212, 15.753] Iran
13 Australia (2.212, 15.753] Australia
14 South America (56.174, 69.648] Brazil

现在,当我使用以下方法将大陆和可再生能源百分比设置为 miltiindex 时:

Top15 = Top15.groupby(by=['Continents', '% Renewable']).sum()

获取以下内容:

                            Country
Continents % Renewable
Asia (15.753, 29.227] China
(2.212, 15.753] JapanIndiaSouth KoreaIran
Australia (2.212, 15.753] Australia
Europe (15.753, 29.227] Russian FederationGermanyFrance
(2.212, 15.753] United Kingdom
(29.227, 42.701] ItalySpain
North America (2.212, 15.753] United States
(56.174, 69.648] Canada
South America (56.174, 69.648] Brazil

现在我想要一个列来显示每个索引中的国家/地区数量,即:

第一行-中国=1,

第二行日本印度韩国伊朗是 4

所以最后我想要这样的东西:

Asia           (2.212, 15.753]     4
(15.753, 29.227] 1

我只是不知道如何到达那里。

此外,数字需要按降序排序,同时仍保持索引分组。

最佳答案

Top15.groupby(['Continents', '% Renewable']).Country.count()

Continents % Renewable
Asia (15.753, 29.227] 1
(2.212, 15.753] 4
Australia (2.212, 15.753] 1
Europe (15.753, 29.227] 3
(2.212, 15.753] 1
(29.227, 42.701] 2
North America (2.212, 15.753] 1
(56.174, 69.648] 1
South America (56.174, 69.648] 1
Name: Country, dtype: int64

按照你喜欢的顺序排序

Top15_count = Top15.groupby(['Continents', '% Renewable']).Country.count()

Top15_count.reset_index() \
.sort_values(
['Continents', 'Country'],
ascending=[True, False]
).set_index(['Continents', '% Renewable']).Country

Continents % Renewable
Asia (2.212, 15.753] 4
(15.753, 29.227] 1
Australia (2.212, 15.753] 1
Europe (15.753, 29.227] 3
(29.227, 42.701] 2
(2.212, 15.753] 1
North America (2.212, 15.753] 1
(56.174, 69.648] 1
South America (56.174, 69.648] 1
Name: Country, dtype: int64

关于python - 连接重复值/行的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41585085/

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