1、排序和排名
根據(jù)條件對數(shù)據(jù)集排序(sorting)也是一種重要的內(nèi)置運(yùn)算。要對行或列索引進(jìn)行排序(按字典順序),可使用sort_index方法,它將返回一個已排序的新對象:
In [80]: obj = pd.Series(range(4), index=['d', 'a', 'b', 'c'])In [81]: obj.sort_index()Out[81]: a 1b 2c 3d 0dtype: int64
而對于DataFrame,則可以根據(jù)任意一個軸上的索引進(jìn)行排序:
In [82]: frame = pd.DataFrame(np.arange(8).reshape((2, 4)), index=['three', 'one'], columns=['d', 'a', 'b', 'c'])In [83]: frame.sort_index()Out[83]: d a b cone 4 5 6 7three 0 1 2 3[2 rows x 4 columns]In [84]: frame.sort_index(axis=1)Out[84]: a b c dthree 1 2 3 0one 5 6 7 4[2 rows x 4 columns]
數(shù)據(jù)默認(rèn)是按升序排序的,但也可以降序排序:
In [85]: frame.sort_index(axis=1, ascending=False)Out[85]: d c b athree 0 3 2 1one 4 7 6 5[2 rows x 4 columns]
若要按值對Series進(jìn)行排序,可使用其order方法:
In [86]: obj = pd.Series([4, 7, -3, 2])In [87]: obj.order()Out[87]: 2 -33 20 41 7dtype: int64
在排序時,任何缺失值默認(rèn)都會被放到Series的末尾:
In [88]: obj = pd.Series([4, np.nan, 7, np.nan, -3, 2])In [89]: obj.order()Out[89]: 4 -35 20 42 71 NaN3 NaNdtype: float64
在DataFrame上,你可能希望根據(jù)一個或多個列中的值進(jìn)行排序。將一個或多個列的名字傳遞給by選項即可達(dá)到該目的:
In [90]: frame = pd.DataFrame({'b': [4, 7, -3, 2], 'a': [0, 1, 0, 1]})In [91]: frameOut[91]: a b0 0 41 1 72 0 -33 1 2[4 rows x 2 columns]In [92]: frame.sort_index(by='b')Out[92]: a b2 0 -33 1 20 0 41 1 7[4 rows x 2 columns]
要根據(jù)多個列進(jìn)行排序,傳入名稱的列表即可:
In [93]: frame.sort_index(by=['a', 'b'])Out[93]: a b2 0 -30 0 43 1 21 1 7[4 rows x 2 columns]
排名(ranking)跟排序關(guān)系密切,且它會增設(shè)一個排名值(從1開始,一直到數(shù)組中有效數(shù)據(jù)的數(shù)量)。它跟numpy.argsort產(chǎn)生的間接排序索引差不多,只不過它可以根據(jù)某種規(guī)則破壞平級關(guān)系。接下來介紹Series和DataFrame的rank方法。默認(rèn)情況下,rank是通過“為各組分配一個平均排名”的方式破壞平級關(guān)系的:
In [95]: obj.rank()Out[95]: 0 6.51 1.02 6.53 4.54 3.05 2.06 4.5dtype: float64
也可以根據(jù)值在原數(shù)據(jù)中出現(xiàn)的順序給出排名:
In [96]: obj.rank(method='first')Out[96]: 0 61 12 73 44 35 26 5dtype: float64
當(dāng)然,你也可以按降序進(jìn)行排名:
In [97]: obj.rank(ascending=False, method='max')Out[97]: 0 21 72 23 44 55 66 4dtype: float64
DataFrame可以在行或列上計算排名:
In [98]: frame = pd.DataFrame({'b': [4.3, 7, -3, 2], 'a': [0, 1, 0, 1], 'c': [-2, 5, 8, -2.5]})In [99]: frameOut[99]: a b c0 0 4.3 -2.01 1 7.0 5.02 0 -3.0 8.03 1 2.0 -2.5[4 rows x 3 columns]In [100]: frame.rank(axis=1)Out[100]: a b c0 2 3 11 1 3 22 2 1 33 2 3 1[4 rows x 3 columns]
2、帶有重復(fù)值的軸索引
直到目前為止,我所介紹的所有范例都有著唯一的軸標(biāo)簽(索引值)。雖然許多pandas函數(shù)(如reindex)都要求標(biāo)簽唯一,但這并不是強(qiáng)制性的。我們來看看下面這個簡單的帶有重復(fù)索引值的Series:
In [101]: obj = pd.Series(range(5), index=['a', 'a', 'b', 'b', 'c'])In [102]: objOut[102]: a 0a 1b 2b 3c 4dtype: int64
索引的is_unique屬性可以告訴你它的值是否是唯一的:
In [103]: obj.index.is_uniqueOut[103]: False
對于帶有重復(fù)值的索引,數(shù)據(jù)選取的行為將會有些不同。如果某個索引對應(yīng)多個值,則返回一個Series;而對應(yīng)單個值的,則返回一個標(biāo)量值。
In [104]: obj['a']Out[104]: a 0a 1dtype: int64In [105]: obj['c']Out[105]: 4
對DataFrame的行進(jìn)行索引時也是如此:
In [107]: df = pd.DataFrame(np.random.randn(4, 3), index=['a', 'a', 'b', 'b'])In [108]: df Out[108]: 0 1 2a 0.863195 0.039140 0.328512a 1.387189 1.878447 1.899090b -1.239626 -0.256105 -0.699475b 0.325932 -0.834134 0.833157[4 rows x 3 columns]In [109]: df.ix['b']Out[109]: 0 1 2b -1.239626 -0.256105 -0.699475b 0.325932 -0.834134 0.833157[2 rows x 3 columns]
3、匯總和計算描述統(tǒng)計
pandas對象擁有一組常用的數(shù)學(xué)和統(tǒng)計方法。它們大部分都屬于約簡和匯總統(tǒng)計,用于從Series中提取單個值(如sum或mean)或從DataFrame的行或列中提取一個Series。跟對應(yīng)的NumPy數(shù)組方法相比,它們都是基于沒有缺失數(shù)據(jù)的假設(shè)而構(gòu)建的。接下來看一個簡單的DataFrame:
In [110]: df = pd.DataFrame([[1.4, np.nan], [7.1, -4.5], [np.nan, np.nan], [0.75, -1.3]], index=['a', 'b', 'c', 'd'], columns=['one', 'two'])In [111]: dfOut[111]: one twoa 1.40 NaNb 7.10 -4.5c NaN NaNd 0.75 -1.3[4 rows x 2 columns]
調(diào)用DataFrame的sum方法將會返回一個含有列小計的Series:
In [112]: df.sum()Out[112]: one 9.25two -5.80dtype: float64
傳入axis=1將會按行進(jìn)行求和運(yùn)算:
In [113]: df.sum(axis=1)Out[113]: a 1.40b 2.60c NaNd -0.55dtype: float64
NA值會自動被排除,除非整個切片(這里值的是行或列)都是NA。通過skipna選項可以禁用該功能:
In [114]: df.mean(axis=1, skipna=False)Out[114]: a NaNb 1.300c NaNd -0.275dtype: float64
有些方法(如idxmin和idxmax)返回的是間接統(tǒng)計(比如達(dá)到最小值或最大值的索引):
In [115]: df.idxmax()Out[115]: one btwo ddtype: object
另一些方法則是累計型的:
In [116]: df.cumsum()Out[116]: one twoa 1.40 NaNb 8.50 -4.5c NaN NaNd 9.25 -5.8[4 rows x 2 columns]
還有一種方法,它既不是約簡型也不是累計型。describe就是一個例子,它用于一次性產(chǎn)生多個匯總統(tǒng)計:
In [117]: df.describe()Out[117]: one twocount 3.000000 2.000000mean 3.083333 -2.900000std 3.493685 2.262742min 0.750000 -4.50000025% 1.075000 -3.70000050% 1.400000 -2.90000075% 4.250000 -2.100000max 7.100000 -1.300000[8 rows x 2 columns]
對于非數(shù)值型數(shù)據(jù),describe會產(chǎn)生另外一種匯總統(tǒng)計:
In [118]: obj = pd.Series(['a', 'a', 'b', 'c'] * 4)In [119]: obj.describe()Out[119]: count 16unique 3top afreq 8dtype: object
4、相關(guān)系數(shù)與協(xié)方差
有些匯總統(tǒng)計(如相關(guān)系數(shù)和協(xié)方差)是通過參數(shù)對計算出來的。我們來看幾個DataFrame,它們的數(shù)據(jù)來自Yahoo! Finance的股票價格和成交量:
import pandas.io.data as weball_data = {}for ticker in ['AAPL', 'IBM', 'MSFT', 'GOOG']: all_data[ticker] = web.get_data_yahoo(ticker, '1/1/2000', '1/1/2010')price = DataFrame({tic: data['Adj Close'] for tic, data in all_data.iteritems()})volume = DataFrame({tic: data['Volume'] for tic, data in all_data.iteritems()})
說明:
雅虎鏈接已經(jīng)失效,不能訪問獲取數(shù)據(jù)。
接下來計算價格的百分?jǐn)?shù)變化:
In [1]: returns = price.pct_change()In [2]: returns.tail()Out[2]: AAPL GOOG IBM MSFTDate 2009-12-24 0.034339 0.011117 0.004420 0.0027472009-12-28 0.012294 0.007098 0.013282 0.0054792009-12-29 -0.011861 -0.005571 -0.003474 0.0068122009-12-30 0.012147 0.005376 0.005468 -0.0135322009-12-31 -0.004300 -0.004416 -0.012609 -0.015432
Series的corr方法用于計算兩個Series中重疊的、非NA的、按索引對齊的值的相關(guān)系數(shù)。與此類似,cov用于計算協(xié)方差:
In [3]: returns.MSFT.corr(returns.IBM)Out[3]: 0.49609291822168838In [4]: returns.MSFT.cov(returns.IBM)Out[4]: 0.00021600332437329015
DataFrame的corr和cov方法將以DataFrame的形式返回完整的相關(guān)系數(shù)或協(xié)方差矩陣:
In [5]: returns.corr()Out[5]: AAPL GOOG IBM MSFTAAPL 1.000000 0.470660 0.410648 0.424550GOOG 0.470660 1.000000 0.390692 0.443334IBM 0.410648 0.390692 1.000000 0.496093MSFT 0.424550 0.443334 0.496093 1.000000In [6]: returns.cov()Out[6]: AAPL GOOG IBM MSFTAAPL 0.001028 0.000303 0.000252 0.000309GOOG 0.000303 0.000580 0.000142 0.000205IBM 0.000252 0.000142 0.000367 0.000216MSFT 0.000309 0.000205 0.000216 0.000516
利用DataFrame的corrwith方法,你可以計算其列或行跟另一個Series或DataFrame之間的相關(guān)系數(shù)。傳入一個Series將會返回一個相關(guān)系數(shù)值Series(針對各列進(jìn)行計算):
In [7]: returns.corrwith(returns.IBM)Out[7]: AAPL 0.410648GOOG 0.390692IBM 1.000000MSFT 0.496093
傳入一個DataFrame則會計算按列名配對的相關(guān)系數(shù)。這里,我計算百分比變化與成交量的相關(guān)系數(shù):
In [8]: returns.corrwith(volume)Out[8]: AAPL -0.057461GOOG 0.062644IBM -0.007900MSFT -0.014175
傳入axis=1即可按行進(jìn)行計算。無論如何,在計算相關(guān)系數(shù)之前,所有的數(shù)據(jù)項都會按標(biāo)簽對齊