栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

按熊猫中的自定义列表排序

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

按熊猫中的自定义列表排序

下面是对数据框执行字典排序的示例。这个想法是基于特定的排序创建一个数字索引。然后根据索引执行数字排序。为此,将一列添加到数据框中,然后将其删除。

import pandas as pd# Create Dataframedf = pd.Dataframe({'id':[2967, 5335, 13950, 6141, 6169],    'Player': ['Cedric Hunter', 'Maurice Baker',    'Ratko Varda' ,'Ryan Bowen' ,'Adrian Caldwell'],    'Year': [1991, 2004, 2001, 2009, 1997],    'Age': [27, 25, 22, 34, 31],    'Tm': ['CHH' ,'VAN' ,'TOT' ,'OKC', 'DAL'],    'G': [6, 7, 60, 52, 81]})# Define the sortersorter = ['TOT', 'ATL', 'BOS', 'BRK', 'CHA', 'CHH', 'CHI', 'CLE', 'DAL','DEN',          'DET', 'GSW', 'HOU', 'IND', 'LAC', 'LAL', 'MEM', 'MIA', 'MIL',          'MIN', 'NJN', 'NOH', 'NOK', 'NOP', 'NYK', 'OKC', 'ORL', 'PHI',          'PHO', 'POR', 'SAC', 'SAS', 'SEA', 'TOR', 'UTA', 'VAN',          'WAS', 'WSB']# Create the dictionary that defines the order for sortingsorterIndex = dict(zip(sorter, range(len(sorter))))# Generate a rank column that will be used to sort# the dataframe numericallydf['Tm_Rank'] = df['Tm'].map(sorterIndex)# Here is the result asked with the lexicographic sort# Result may be hard to analyze, so a second sorting is# proposed next## NOTE: ## Newer versions of pandas use 'sort_values' instead of 'sort'df.sort_values(['Player', 'Year', 'Tm_Rank'],        ascending = [True, True, True], inplace = True)df.drop('Tm_Rank', 1, inplace = True)print(df)# Here is an example where 'Tm' is sorted first, that will # give the first row of the Dataframe df to contain TOT as 'Tm'df['Tm_Rank'] = df['Tm'].map(sorterIndex)## NOTE: ## Newer versions of pandas use 'sort_values' instead of 'sort'df.sort_values(['Tm_Rank', 'Player', 'Year'],        ascending = [True , True, True], inplace = True)df.drop('Tm_Rank', 1, inplace = True)print(df)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/429129.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号