python:series一些函数用法
生活随笔
收集整理的這篇文章主要介紹了
python:series一些函数用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
相關:DataFrame一些函數用法
目錄
- series
- reindex
- Series排序
- 統計和計算
series
性質:一維數組對象,類似NumPy 的一維array。
(除了包含一組數據還包含一組索引,所以可以把它理解為一組帶索引的數組。)
reindex
reindex方法重新設定了一組數據的索引,如果索引在原數據中沒有匹配,則以NaN填充。
import pandas as pd from pandas import Series, DataFrame obj = Series([4.5, 7.2, -5.3, 3.6], index = ['d', 'b', 'a', 'c']) #reindex用法示例 obj2 = obj.reindex(['a', 'b', 'c', 'd', 'e']) obj2 輸出:a -5.3 b 7.2 c 3.6 d 4.5 e NaN dtype: float64如果不想以NaN填充呢?可以用fill_value方法來設置。
obj.reindex(['a', 'b', 'c', 'd', 'e'], fill_value = 0) 輸出:a -5.3 b 7.2 c 3.6 d 4.5 e 0.0 dtype: float64也可以用ffill方法實現前向填充,也就是補充的索引如果沒有對應的數值,則取前一個索引的值填充;或者用bfill方法實現后向填充,也就是補充的索引如果沒有對應的數值,則取后一個索引的值填充
obj3 = Series(['blue', 'purple', 'yellow'], index = [0, 2, 4]) obj3 輸出:0 blue 2 purple 4 yellow dtype: object#使用ffill實現前向值填充 obj3.reindex(range(6), method = 'ffill') 輸出:0 blue 1 blue 2 purple 3 purple 4 yellow 5 yellow dtype: object#使用bfill實現前向值填充 obj3.reindex(range(5), method = 'bfill') 輸出:0 blue 1 purple 2 purple 3 yellow 4 yellow dtype: objectSeries排序
series=pd.Series([3,4,1,6],index=['b','a','d','c']) series 輸出 b 3 a 4 d 1 c 6 dtype: int64# 'series通過索引進行排序:' series.sort_index() 輸出 a 4 b 3 c 6 d 1 dtype: int64#'series通過值進行排序:' series.sort_values() 輸出 d 1 b 3 a 4 c 6 dtype: int64統計和計算
obj = Series([1,2,3,4,1,2,5],index=list('abcdefg')) obj 輸出 a 1 b 2 c 3 d 4 e 1 f 2 g 5 dtype: int64obj.unique() 輸出 array([1, 2, 3, 4, 5], dtype=int64)set(obj) 輸出 {1, 2, 3, 4, 5}obj.value_counts() 輸出 2 2 1 2 5 1 4 1 3 1 dtype: int64from collections import Counter Counter(obj) 輸出 Counter({1: 2, 2: 2, 3: 1, 4: 1, 5: 1})參考:
Python之DataFrame常用方法小結
Python學習筆記(6):Pandas的reindex方法
Python中的lambda和apply用法
python學習筆記—DataFrame和Series的排序
總結
以上是生活随笔為你收集整理的python:series一些函数用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python:pandas之read_c
- 下一篇: python:dataframe