溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

pandas的使用技巧

發(fā)布時間:2020-10-10 16:51:25 來源:億速云 閱讀:149 作者:小新 欄目:編程語言

小編給大家分享一下pandas的使用技巧,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

pandas有一種功能非常強大的方法,它就是accessor,可以將它理解為一種屬性接口,通過它可以獲得額外的方法。其實這樣說還是很籠統(tǒng),下面我們通過代碼和實例來理解一下。

>>> pd.Series._accessors
{'cat', 'str', 'dt'}復(fù)制代碼

對于Series數(shù)據(jù)結(jié)構(gòu)使用_accessors方法,我們得到了3個對象:cat,str,dt。

  • .cat:用于分類數(shù)據(jù)(Categorical data)
  • .str:用于字符數(shù)據(jù)(String Object data)
  • .dt:用于時間數(shù)據(jù)(datetime-like data)

下面我們依次看一下這三個對象是如何使用的。

str對象的使用

Series數(shù)據(jù)類型:str字符串

# 定義一個Series序列
>>> addr = pd.Series([
...     'Washington, D.C. 20003',
...     'Brooklyn, NY 11211-1755',
...     'Omaha, NE 68154',
...     'Pittsburgh, PA 15211'
... ]) 

>>> addr.str.upper()
0     WASHINGTON, D.C. 20003
1    BROOKLYN, NY 11211-1755
2            OMAHA, NE 68154
3       PITTSBURGH, PA 15211
dtype: object

>>> addr.str.count(r'\d') 
0    5
1    9
2    5
3    5
dtype: int64復(fù)制代碼

關(guān)于以上str對象的2個方法說明:

  • Series.str.upper:將Series中所有字符串變?yōu)榇髮懀?/li>
  • Series.str.count:對Series中所有字符串的個數(shù)進行計數(shù);

其實不難發(fā)現(xiàn),該用法的使用與Python中字符串的操作很相似。沒錯,在pandas中你一樣可以這樣簡單的操作,而不同的是你操作的是一整列的字符串數(shù)據(jù)。仍然基于以上數(shù)據(jù)集,再看它的另一個操作:

>>> regex = (r'(?P<city>[A-Za-z ]+), '      # 一個或更多字母
...          r'(?P<state>[A-Z]{2}) '        # 兩個大寫字母
...          r'(?P<zip>\d{5}(?:-\d{4})?)')  # 可選的4個延伸數(shù)字
...
>>> addr.str.replace('.', '').str.extract(regex)
         city state         zip
0  Washington    DC       20003
1    Brooklyn    NY  11211-1755
2       Omaha    NE       68154
3  Pittsburgh    PA       15211復(fù)制代碼

關(guān)于以上str對象的2個方法說明:

  • Series.str.replace:將Series中指定字符串替換;
  • Series.str.extract:通過正則表達式提取字符串中的數(shù)據(jù)信息;

這個用法就有點復(fù)雜了,因為很明顯看到,這是一個鏈式的用法。通過replace將 " . " 替換為"",即為空,緊接著又使用了3個正則表達式(分別對應(yīng)city,state,zip)通過extract對數(shù)據(jù)進行了提取,并由原來的Series數(shù)據(jù)結(jié)構(gòu)變?yōu)榱薉ataFrame數(shù)據(jù)結(jié)構(gòu)。

當然,除了以上用法外,常用的屬性和方法還有.rstrip,.contains,split等,我們通過下面代碼查看一下str屬性的完整列表:

>>> [i for i in dir(pd.Series.str) if not i.startswith('_')]
['capitalize',
 'cat',
 'center',
 'contains',
 'count',
 'decode',
 'encode',
 'endswith',
 'extract',
 'extractall',
 'find',
 'findall',
 'get',
 'get_dummies',
 'index',
 'isalnum',
 'isalpha',
 'isdecimal',
 'isdigit',
 'islower',
 'isnumeric',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'len',
 'ljust',
 'lower',
 'lstrip',
 'match',
 'normalize',
 'pad',
 'partition',
 'repeat',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'slice',
 'slice_replace',
 'split',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'wrap',
 'zfill']復(fù)制代碼

屬性有很多,對于具體的用法,如果感興趣可以自己進行摸索練習(xí)。

dt對象的使用

Series數(shù)據(jù)類型:datetime

因為數(shù)據(jù)需要datetime類型,所以下面使用pandas的date_range()生成了一組日期datetime演示如何進行dt對象操作。

>>> daterng = pd.Series(pd.date_range('2017', periods=9, freq='Q'))
>>> daterng
0   2017-03-31
1   2017-06-30
2   2017-09-30
3   2017-12-31
4   2018-03-31
5   2018-06-30
6   2018-09-30
7   2018-12-31
8   2019-03-31
dtype: datetime64[ns]

>>>  daterng.dt.day_name()
0      Friday
1      Friday
2    Saturday
3      Sunday
4    Saturday
5    Saturday
6      Sunday
7      Monday
8      Sunday
dtype: object

>>> # 查看下半年
>>> daterng[daterng.dt.quarter > 2]
2   2017-09-30
3   2017-12-31
6   2018-09-30
7   2018-12-31
dtype: datetime64[ns]

>>> daterng[daterng.dt.is_year_end]
3   2017-12-31
7   2018-12-31
dtype: datetime64[ns]復(fù)制代碼

以上關(guān)于dt的3種方法說明:

  • Series.dt.day_name():從日期判斷出所處星期數(shù);
  • Series.dt.quarter:從日期判斷所處季節(jié);
  • Series.dt.is_year_end:從日期判斷是否處在年底;

其它方法也都是基于datetime的一些變換,并通過變換來查看具體微觀或者宏觀日期。

cat對象的使用

Series數(shù)據(jù)類型:Category

在說cat對象的使用前,先說一下Category這個數(shù)據(jù)類型,它的作用很強大。雖然我們沒有經(jīng)常性的在內(nèi)存中運行上g的數(shù)據(jù),但是我們也總會遇到執(zhí)行幾行代碼會等待很久的情況。使用Category數(shù)據(jù)的一個好處就是:可以很好的節(jié)省在時間和空間的消耗。下面我們通過幾個實例來學(xué)習(xí)一下。

>>> colors = pd.Series([
...     'periwinkle',
...     'mint green',
...     'burnt orange',
...     'periwinkle',
...     'burnt orange',
...     'rose',
...     'rose',
...     'mint green',
...     'rose',
...     'navy'
... ])
...
>>> import sys
>>> colors.apply(sys.getsizeof)
0    59
1    59
2    61
3    59
4    61
5    53
6    53
7    59
8    53
9    53
dtype: int64復(fù)制代碼

上面我們通過使用sys.getsizeof來顯示內(nèi)存占用的情況,數(shù)字代表字節(jié)數(shù)。
還有另一種計算內(nèi)容占用的方法:memory_usage(),后面會使用。

現(xiàn)在我們將上面colors的不重復(fù)值映射為一組整數(shù),然后再看一下占用的內(nèi)存。

>>> mapper = {v: k for k, v in enumerate(colors.unique())}
>>> mapper
{'periwinkle': 0, 'mint green': 1, 'burnt orange': 2, 'rose': 3, 'navy': 4}

>>> as_int = colors.map(mapper)
>>> as_int
0    0
1    1
2    2
3    0
4    2
5    3
6    3
7    1
8    3
9    4
dtype: int64

>>> as_int.apply(sys.getsizeof)
0    24
1    28
2    28
3    24
4    28
5    28
6    28
7    28
8    28
9    28
dtype: int64復(fù)制代碼

注:對于以上的整數(shù)值映射也可以使用更簡單的pd.factorize()方法代替。

我們發(fā)現(xiàn)上面所占用的內(nèi)存是使用object類型時的一半。其實,這種情況就類似于Category data類型內(nèi)部的原理。

內(nèi)存占用區(qū)別:Categorical所占用的內(nèi)存與Categorical分類的數(shù)量和數(shù)據(jù)的長度成正比,相反,object所占用的內(nèi)存則是一個常數(shù)乘以數(shù)據(jù)的長度。

下面是object內(nèi)存使用和category內(nèi)存使用的情況對比。

>>> colors.memory_usage(index=False, deep=True)
650
>>> colors.astype('category').memory_usage(index=False, deep=True)
495復(fù)制代碼

上面結(jié)果是使用object和Category兩種情況下內(nèi)存的占用情況。我們發(fā)現(xiàn)效果并沒有我們想象中的那么好。但是注意Category內(nèi)存是成比例的,如果數(shù)據(jù)集的數(shù)據(jù)量很大,但不重復(fù)分類(unique)值很少的情況下,那么Category的內(nèi)存占用可以節(jié)省達到10倍以上,比如下面數(shù)據(jù)量增大的情況:

>>> manycolors = colors.repeat(10)
>>> len(manycolors) / manycolors.nunique() 
20.0

>>> manycolors.memory_usage(index=False, deep=True)
6500
>>> manycolors.astype('category').memory_usage(index=False, deep=True)
585復(fù)制代碼

可以看到,在數(shù)據(jù)量增加10倍以后,使用Category所占內(nèi)容節(jié)省了10倍以上。

除了占用內(nèi)存節(jié)省外,另一個額外的好處是計算效率有了很大的提升。因為對于Category類型的Series,str字符的操作發(fā)生在.cat.categories的非重復(fù)值上,而并非原Series上的所有元素上。也就是說對于每個非重復(fù)值都只做一次操作,然后再向與非重復(fù)值同類的值映射過去。

對于Category的數(shù)據(jù)類型,可以使用accessor的cat對象,以及相應(yīng)的屬性和方法來操作Category數(shù)據(jù)。

>>> ccolors = colors.astype('category')
>>> ccolors.cat.categories
Index(['burnt orange', 'mint green', 'navy', 'periwinkle', 'rose'], dtype='object')復(fù)制代碼

實際上,對于開始的整數(shù)類型映射,我們可以先通過reorder_categories進行重新排序,然后再使用cat.codes來實現(xiàn)對整數(shù)的映射,來達到同樣的效果。

>>> ccolors.cat.reorder_categories(mapper).cat.codes
0    0
1    1
2    2
3    0
4    2
5    3
6    3
7    1
8    3
9    4
dtype: int8復(fù)制代碼

dtype類型是Numpy的int8(-127~128)。可以看出以上只需要一個單字節(jié)就可以在內(nèi)存中包含所有的值。我們開始的做法默認使用了int64類型,然而通過pandas的使用可以很智能的將Category數(shù)據(jù)類型變?yōu)樽钚〉念愋汀?/p>

讓我們來看一下cat還有什么其它的屬性和方法可以使用。下面cat的這些屬性基本都是關(guān)于查看和操作Category數(shù)據(jù)類型的。

>>> [i for i in dir(ccolors.cat) if not i.startswith('_')]
['add_categories',
 'as_ordered',
 'as_unordered',
 'categories',
 'codes',
 'ordered',
 'remove_categories',
 'remove_unused_categories',
 'rename_categories',
 'reorder_categories',
 'set_categories']復(fù)制代碼

但是Category數(shù)據(jù)的使用不是很靈活。例如,插入一個之前沒有的值,首先需要將這個值添加到.categories的容器中,然后再添加值。

>>> ccolors.iloc[5] = 'a new color'
# ...
ValueError: Cannot setitem on a Categorical with a new category,
set the categories first

>>> ccolors = ccolors.cat.add_categories(['a new color'])
>>> ccolors.iloc[5] = 'a new color'  
復(fù)制代碼

如果你想設(shè)置值或重塑數(shù)據(jù),而非進行新的運算操作,那么Category類型不是那么有用。

以上是pandas的使用技巧的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI