如何利用python进行数据分析统计服_利用Python进行数据分析
1、排序和排名
根據條件對數據集排序(sorting)也是一種重要的內置運算。要對行或列索引進行排序(按字典順序),可使用sort_index方法,它將返回一個已排序的新對象:
In [80]: obj = pd.Series(range(4), index=['d', 'a', 'b', 'c'])
In [81]: obj.sort_index()
Out[81]:
a 1
b 2
c 3
d 0
dtype: int64
而對于DataFrame,則可以根據任意一個軸上的索引進行排序:
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 c
one 4 5 6 7
three 0 1 2 3
[2 rows x 4 columns]
In [84]: frame.sort_index(axis=1)
Out[84]:
a b c d
three 1 2 3 0
one 5 6 7 4
[2 rows x 4 columns]
數據默認是按升序排序的,但也可以降序排序:
In [85]: frame.sort_index(axis=1, ascending=False)
Out[85]:
d c b a
three 0 3 2 1
one 4 7 6 5
[2 rows x 4 columns]
若要按值對Series進行排序,可使用其order方法:
In [86]: obj = pd.Series([4, 7, -3, 2])
In [87]: obj.order()
Out[87]:
2 -3
3 2
0 4
1 7
dtype: int64
在排序時,任何缺失值默認都會被放到Series的末尾:
In [88]: obj = pd.Series([4, np.nan, 7, np.nan, -3, 2])
In [89]: obj.order()
Out[89]:
4 -3
5 2
0 4
2 7
1 NaN
3 NaN
dtype: float64
在DataFrame上,你可能希望根據一個或多個列中的值進行排序。將一個或多個列的名字傳遞給by選項即可達到該目的:
In [90]: frame = pd.DataFrame({'b': [4, 7, -3, 2], 'a': [0, 1, 0, 1]})
In [91]: frame
Out[91]:
a b
0 0 4
1 1 7
2 0 -3
3 1 2
[4 rows x 2 columns]
In [92]: frame.sort_index(by='b')
Out[92]:
a b
2 0 -3
3 1 2
0 0 4
1 1 7
[4 rows x 2 columns]
要根據多個列進行排序,傳入名稱的列表即可:
In [93]: frame.sort_index(by=['a', 'b'])
Out[93]:
a b
2 0 -3
0 0 4
3 1 2
1 1 7
[4 rows x 2 columns]
排名(ranking)跟排序關系密切,且它會增設一個排名值(從1開始,一直到數組中有效數據的數量)。它跟numpy.argsort產生的間接排序索引差不多,只不過它可以根據某種規則破壞平級關系。接下來介紹Series和DataFrame的rank方法。默認情況下,rank是通過“為各組分配一個平均排名”的方式破壞平級關系的:
In [95]: obj.rank()
Out[95]:
0 6.5
1 1.0
2 6.5
3 4.5
4 3.0
5 2.0
6 4.5
dtype: float64
也可以根據值在原數據中出現的順序給出排名:
In [96]: obj.rank(method='first')
Out[96]:
0 6
1 1
2 7
3 4
4 3
5 2
6 5
dtype: float64
當然,你也可以按降序進行排名:
In [97]: obj.rank(ascending=False, method='max')
Out[97]:
0 2
1 7
2 2
3 4
4 5
5 6
6 4
dtype: 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]: frame
Out[99]:
a b c
0 0 4.3 -2.0
1 1 7.0 5.0
2 0 -3.0 8.0
3 1 2.0 -2.5
[4 rows x 3 columns]
In [100]: frame.rank(axis=1)
Out[100]:
a b c
0 2 3 1
1 1 3 2
2 2 1 3
3 2 3 1
[4 rows x 3 columns]
2、帶有重復值的軸索引
直到目前為止,我所介紹的所有范例都有著唯一的軸標簽(索引值)。雖然許多pandas函數(如reindex)都要求標簽唯一,但這并不是強制性的。我們來看看下面這個簡單的帶有重復索引值的Series:
In [101]: obj = pd.Series(range(5), index=['a', 'a', 'b', 'b', 'c'])
In [102]: obj
Out[102]:
a 0
a 1
b 2
b 3
c 4
dtype: int64
索引的is_unique屬性可以告訴你它的值是否是唯一的:
In [103]: obj.index.is_unique
Out[103]: False
對于帶有重復值的索引,數據選取的行為將會有些不同。如果某個索引對應多個值,則返回一個Series;而對應單個值的,則返回一個標量值。
In [104]: obj['a']
Out[104]:
a 0
a 1
dtype: int64
In [105]: obj['c']
Out[105]: 4
對DataFrame的行進行索引時也是如此:
In [107]: df = pd.DataFrame(np.random.randn(4, 3), index=['a', 'a', 'b', 'b'])
In [108]: df
Out[108]:
0 1 2
a 0.863195 0.039140 0.328512
a 1.387189 1.878447 1.899090
b -1.239626 -0.256105 -0.699475
b 0.325932 -0.834134 0.833157
[4 rows x 3 columns]
In [109]: df.ix['b']
Out[109]:
0 1 2
b -1.239626 -0.256105 -0.699475
b 0.325932 -0.834134 0.833157
[2 rows x 3 columns]
3、匯總和計算描述統計
pandas對象擁有一組常用的數學和統計方法。它們大部分都屬于約簡和匯總統計,用于從Series中提取單個值(如sum或mean)或從DataFrame的行或列中提取一個Series。跟對應的NumPy數組方法相比,它們都是基于沒有缺失數據的假設而構建的。接下來看一個簡單的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]: df
Out[111]:
one two
a 1.40 NaN
b 7.10 -4.5
c NaN NaN
d 0.75 -1.3
[4 rows x 2 columns]
調用DataFrame的sum方法將會返回一個含有列小計的Series:
In [112]: df.sum()
Out[112]:
one 9.25
two -5.80
dtype: float64
傳入axis=1將會按行進行求和運算:
In [113]: df.sum(axis=1)
Out[113]:
a 1.40
b 2.60
c NaN
d -0.55
dtype: float64
NA值會自動被排除,除非整個切片(這里值的是行或列)都是NA。通過skipna選項可以禁用該功能:
In [114]: df.mean(axis=1, skipna=False)
Out[114]:
a NaN
b 1.300
c NaN
d -0.275
dtype: float64
有些方法(如idxmin和idxmax)返回的是間接統計(比如達到最小值或最大值的索引):
In [115]: df.idxmax()
Out[115]:
one b
two d
dtype: object
另一些方法則是累計型的:In [116]: df.cumsum()
Out[116]:
one two
a 1.40 NaN
b 8.50 -4.5
c NaN NaN
d 9.25 -5.8
[4 rows x 2 columns]
還有一種方法,它既不是約簡型也不是累計型。describe就是一個例子,它用于一次性產生多個匯總統計:
In [117]: df.describe()
Out[117]:
one two
count 3.000000 2.000000
mean 3.083333 -2.900000
std 3.493685 2.262742
min 0.750000 -4.500000
25% 1.075000 -3.700000
50% 1.400000 -2.900000
75% 4.250000 -2.100000
max 7.100000 -1.300000
[8 rows x 2 columns]
對于非數值型數據,describe會產生另外一種匯總統計:
In [118]: obj = pd.Series(['a', 'a', 'b', 'c'] * 4)
In [119]: obj.describe()
Out[119]:
count 16
unique 3
top a
freq 8
dtype: object
4、相關系數與協方差
有些匯總統計(如相關系數和協方差)是通過參數對計算出來的。我們來看幾個DataFrame,它們的數據來自Yahoo! Finance的股票價格和成交量:
import pandas.io.data as web
all_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()})
說明:
雅虎鏈接已經失效,不能訪問獲取數據。
接下來計算價格的百分數變化:
In [1]: returns = price.pct_change()
In [2]: returns.tail()
Out[2]:
AAPL GOOG IBM MSFT
Date
2009-12-24 0.034339 0.011117 0.004420 0.002747
2009-12-28 0.012294 0.007098 0.013282 0.005479
2009-12-29 -0.011861 -0.005571 -0.003474 0.006812
2009-12-30 0.012147 0.005376 0.005468 -0.013532
2009-12-31 -0.004300 -0.004416 -0.012609 -0.015432
Series的corr方法用于計算兩個Series中重疊的、非NA的、按索引對齊的值的相關系數。與此類似,cov用于計算協方差:
In [3]: returns.MSFT.corr(returns.IBM)
Out[3]: 0.49609291822168838
In [4]: returns.MSFT.cov(returns.IBM)
Out[4]: 0.00021600332437329015
DataFrame的corr和cov方法將以DataFrame的形式返回完整的相關系數或協方差矩陣:
In [5]: returns.corr()
Out[5]:
AAPL ? ? GOOG ? ? ?IBM ? ? MSFT
AAPL 1.000000 0.470660 0.410648 0.424550
GOOG 0.470660 1.000000 0.390692 0.443334
IBM ?0.410648 0.390692 1.000000 0.496093
MSFT 0.424550 0.443334 0.496093 1.000000
In [6]: returns.cov()
Out[6]:
AAPL ? ? GOOG ? ? ?IBM ? ? MSFT
AAPL 0.001028 0.000303 0.000252 0.000309
GOOG 0.000303 0.000580 0.000142 0.000205
IBM ?0.000252 0.000142 0.000367 0.000216
MSFT 0.000309 0.000205 0.000216 0.000516
利用DataFrame的corrwith方法,你可以計算其列或行跟另一個Series或DataFrame之間的相關系數。傳入一個Series將會返回一個相關系數值Series(針對各列進行計算):
In [7]: returns.corrwith(returns.IBM)
Out[7]:
AAPL 0.410648
GOOG 0.390692
IBM ?1.000000
MSFT 0.496093
傳入一個DataFrame則會計算按列名配對的相關系數。這里,我計算百分比變化與成交量的相關系數:
In [8]: returns.corrwith(volume)
Out[8]:
AAPL -0.057461
GOOG ?0.062644
IBM ?-0.007900
MSFT -0.014175
傳入axis=1即可按行進行計算。無論如何,在計算相關系數之前,所有的數據項都會按標簽對齊
總結
以上是生活随笔為你收集整理的如何利用python进行数据分析统计服_利用Python进行数据分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: tensorflow怎样调用gpu_te
- 下一篇: 微软的python开发工具_面向 Pyt