1. 程式人生 > >Python: Pandas的DataFrame如何按指定list排序

Python: Pandas的DataFrame如何按指定list排序

不同 需求 per log title 表示 anr lac 使用

本文首發於微信公眾號“Python數據之道”(ID:PyDataRoad)

前言

寫這篇文章的起由是有一天微信上一位朋友問到一個問題,問題大體意思概述如下:

現在有一個pandas的Series和一個python的list,想讓Series按指定的list進行排序,如何實現?

這個問題的需求用流程圖描述如下:

技術分享

我思考了一下,這個問題解決的核心是引入pandas的數據類型“category”,從而進行排序。

在具體的分析過程中,先將pandas的Series轉換成為DataFrame,然後設置數據類型,再進行排序。思路用流程圖表示如下:

技術分享

分析過程

  • 引入pandas庫
import pandas as pd
  • 構造Series數據
s = pd.Series({‘a‘:1,‘b‘:2,‘c‘:3})
s
a    1
b    2
c    3
dtype: int64
s.index
Index([‘a‘, ‘b‘, ‘c‘], dtype=‘object‘)
  • 指定的list,後續按指定list的元素順序進行排序
list_custom = [‘b‘, ‘a‘, ‘c‘]
list_custom
[‘b‘, ‘a‘, ‘c‘]
  • 將Series轉換成DataFrame
    df = pd.DataFrame(s)
    df = df.reset_index()
    df.columns = [‘words‘
    , ‘number‘] df

wordsnumber
0 a 1
1 b 2
2 c 3

設置成“category”數據類型

# 設置成“category”數據類型
df[‘words‘] = df[‘words‘].astype(‘category‘)
# inplace = True,使 recorder_categories生效
df[‘words‘
].cat.reorder_categories(list_custom, inplace=True) # inplace = True,使 df生效 df.sort_values(‘words‘, inplace=True) df

wordsnumber
1 b 2
0 a 1
2 c 3

指定list元素多的情況:

若指定的list所包含元素比Dataframe中需要排序的列的元素,怎麽辦?

  • reorder_catgories()方法不能繼續使用,因為該方法使用時要求新的categories和dataframe中的categories的元素個數和內容必須一致,只是順序不同。
  • 這種情況下,可以使用 set_categories()方法來實現。新的list可以比dataframe中元素多。
list_custom_new = [‘d‘, ‘c‘, ‘b‘,‘a‘,‘e‘]
dict_new = {‘e‘:1, ‘b‘:2, ‘c‘:3}
df_new = pd.DataFrame(list(dict_new.items()), columns=[‘words‘, ‘value‘])
print(list_custom_new)
df_new.sort_values(‘words‘, inplace=True)
df_new
[‘d‘, ‘c‘, ‘b‘, ‘a‘, ‘e‘]

wordsvalue
0 b 2
1 c 3
2 e 1
df_new[‘words‘] = df_new[‘words‘].astype(‘category‘)

# inplace = True,使 set_categories生效
df_new[‘words‘].cat.set_categories(list_custom_new, inplace=True)

df_new.sort_values(‘words‘, ascending=True)

wordsvalue
1 c 3
0 b 2
2 e 1

指定list元素少的情況:

若指定的list所包含元素比Dataframe中需要排序的列的元素,怎麽辦?

  • 這種情況下,set_categories()方法還是可以使用的,只是沒有的元素會以NaN表示

註意下面的list中沒有元素“b”

list_custom_new = [‘d‘, ‘c‘,‘a‘,‘e‘]
dict_new = {‘e‘:1, ‘b‘:2, ‘c‘:3}
df_new = pd.DataFrame(list(dict_new.items()), columns=[‘words‘, ‘value‘])
print(list_custom_new)
df_new.sort_values(‘words‘, inplace=True)
df_new
[‘d‘, ‘c‘, ‘a‘, ‘e‘]

wordsvalue
0 b 2
1 c 3
2 e 1
df_new[‘words‘] = df_new[‘words‘].astype(‘category‘)

# inplace = True,使 set_categories生效
df_new[‘words‘].cat.set_categories(list_custom_new, inplace=True)

df_new.sort_values(‘words‘, ascending=True)

wordsvalue
0 NaN 2
1 c 3
2 e 1

總結

根據指定的list所包含元素比Dataframe中需要排序的列的元素的多或少,可以分為三種情況:

  • 相等的情況下,可以使用 reorder_categories和 set_categories方法;
  • list的元素比較多的情況下, 可以使用set_categories方法;
  • list的元素比較少的情況下, 也可以使用set_categories方法,但list中沒有的元素會在DataFrame中以NaN表示。

源代碼

需要的童鞋可在微信公眾號“Python數據之道”(ID:PyDataRoad)後臺回復關鍵字獲取視頻,關鍵字如下:

2017-025”(不含引號)

?

Python: Pandas的DataFrame如何按指定list排序