gpt4 book ai didi

pandas - 数据框中的排序/字母顺序列(Pandas)

转载 作者:行者123 更新时间:2023-12-02 15:17:26 24 4
gpt4 key购买 nike

我无法按字母顺序排列数据框第一列和第二列中的名称。

数据框看起来像这样:

          Boys       Females
Rank
1 Michael Jennifer
2 Christopher Jessica
3 Matthew Amanda
4 Jason Sarah
5 David Melissa
6 Joshua Amy
7 James Nicole
8 John Stephanie
9 Robert Elizabeth
10 Daniel Heather
11 Joseph Michelle
12 Justin Rebecca
13 Ryan Kimberly
14 Brian Tiffany

我希望它看起来像这样:(男孩和女性的名字按字母顺序排列)

 Rank     Boys                 Rank    Females
14 Brian 3 Amanda
2 Christopher 6 Amy
10 Daniel 9 Elizabeth
5 David 10 Heather
7 James 1 Jennifer

我尝试过 sort 和 sort_value 但列没有改变。这是我的原始代码

import pandas as pd



df = pd.read_html("file:///C:/Python27/babyname999.html")

df2 =df[0] # creating a data frame from the above list of dateframes

df2.rename(columns = {'0': 'Rank', '1': 'Boys', '2': 'Females'}, inplace = True)
del df2['Unnamed: 0']

#renaming columns of dataframe


df2.set_index('Rank', inplace = True) #setting index of dataframe to 'Rank'

我尝试过 sort 和 sort_value 但列没有改变。我不知道在哪里。有什么建议吗?

谢谢!

最佳答案

这是排序的工作示例。

import pandas as pd
from io import StringIO

data_file = StringIO(u"""Rank Boys Females
1 Michael Jennifer
2 Christopher Jessica
3 Matthew Amanda
4 Jason Sarah
5 David Melissa
6 Joshua Amy
7 James Nicole
8 John Stephanie
9 Robert Elizabeth
10 Daniel Heather
11 Joseph Michelle
12 Justin Rebecca
13 Ryan Kimberly
14 Brian Tiffany""")

df = pd.read_table(data_file, delim_whitespace=True)

boys = df[['Rank','Boys']].sort_values(['Boys']).rename(columns={'Rank': 'Rank_boys'})
females = df[['Rank','Females']].sort_values(['Females']).rename(columns={'Rank': 'Rank_females'})
result = pd.concat([boys.reset_index(drop=True), females.reset_index(drop=True)], axis=1)

结果是:

Rank_boys Boys Rank_females Females
0 14 Brian 3 Amanda
1 2 Christopher 6 Amy
2 10 Daniel 9 Elizabeth
3 5 David 10 Heather
4 7 James 1 Jennifer
5 4 Jason 2 Jessica
6 8 John 13 Kimberly
7 11 Joseph 5 Melissa
8 6 Joshua 11 Michelle
9 12 Justin 7 Nicole
10 3 Matthew 12 Rebecca
11 1 Michael 4 Sarah
12 9 Robert 8 Stephanie
13 13 Ryan 14 Tiffany

关于pandas - 数据框中的排序/字母顺序列(Pandas),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39429614/

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