版本 0.11.0 (2013 年 4 月 22 日)#
這是從 0.10.1 版本開始的一個主要版本釋出,包含許多新功能和增強功能,以及大量的錯誤修復。資料選擇方法的添加了許多新內容,並且 Dtype 支援已趨於完善。此外,還有一些重要的 API 更改,長期使用 pandas 的使用者應密切關注。
文件中新增了一個部分,10 分鐘掌握 pandas,主要面向新使用者。
文件中新增了一個部分,Cookbook,收集了 pandas 中一些有用的技巧(我們希望收到您的貢獻!)。
現在有幾個庫是推薦的依賴項
選擇選項#
從 0.11.0 版本開始,為了支援更明確的基於位置的索引,物件選擇增加了一些使用者要求的新增。pandas 現在支援三種多軸索引型別。
.loc嚴格基於標籤,當找不到專案時將引發KeyError,允許的輸入包括:單個標籤,例如
5或'a',(請注意5被解釋為索引的標籤。此用法不是索引上的整數位置)標籤列表或陣列
['a', 'b', 'c']帶有標籤的切片物件
'a':'f',(請注意,與普通的 python 切片不同,開始和結束都包含在內!)布林陣列
更多資訊請參見 按標籤選擇
.iloc嚴格基於整數位置(從0到軸的length-1),當請求的索引超出範圍時將引發IndexError。允許的輸入包括:整數,例如
5整數列表或陣列
[4, 3, 0]帶有整數的切片物件
1:7布林陣列
更多資訊請參見 按位置選擇
.ix支援混合整數和基於標籤的訪問。它主要基於標籤,但會回退到整數位置訪問。.ix是最通用的,它將支援.loc和.iloc的任何輸入,以及對浮點標籤方案的支援。.ix在處理混合位置和基於標籤的分層索引時尤其有用。由於在使用
.ix時,整數切片的使用行為取決於切片被解釋為基於位置還是基於標籤,因此通常最好明確使用.iloc或.loc。
選擇棄用#
從 0.11.0 版本開始,這些方法在未來版本中可能會被棄用。
irowicoliget_value
請參閱 按位置選擇 部分以獲取替代方法。
Dtypes#
數值 dtype 將會傳播,並且可以在 DataFrames 中共存。如果傳遞了 dtype(無論是直接透過 dtype 關鍵字、傳遞的 ndarray,還是傳遞的 Series),那麼它將在 DataFrame 操作中得到保留。此外,不同的數值 dtype **不會**被合併。下面的示例將讓你對此有所瞭解。
In [1]: df1 = pd.DataFrame(np.random.randn(8, 1), columns=['A'], dtype='float64')
In [2]: df1
Out[2]:
A
0 0.469112
1 -0.282863
2 -1.509059
3 -1.135632
4 1.212112
5 -0.173215
6 0.119209
7 -1.044236
In [3]: df1.dtypes
Out[3]:
A float64
dtype: object
In [4]: df2 = pd.DataFrame({'A': pd.Series(np.random.randn(8), dtype='float32'),
...: 'B': pd.Series(np.random.randn(8)),
...: 'C': pd.Series(range(8), dtype='uint8')})
...:
In [5]: df2
Out[5]:
A B C
0 -0.861849 -0.424972 0
1 -2.104569 0.567020 1
2 -0.494929 0.276232 2
3 1.071804 -1.087401 3
4 0.721555 -0.673690 4
5 -0.706771 0.113648 5
6 -1.039575 -1.478427 6
7 0.271860 0.524988 7
In [6]: df2.dtypes
Out[6]:
A float32
B float64
C uint8
dtype: object
# here you get some upcasting
In [7]: df3 = df1.reindex_like(df2).fillna(value=0.0) + df2
In [8]: df3
Out[8]:
A B C
0 -0.392737 -0.424972 0.0
1 -2.387433 0.567020 1.0
2 -2.003988 0.276232 2.0
3 -0.063829 -1.087401 3.0
4 1.933667 -0.673690 4.0
5 -0.879986 0.113648 5.0
6 -0.920366 -1.478427 6.0
7 -0.772376 0.524988 7.0
In [9]: df3.dtypes
Out[9]:
A float64
B float64
C float64
dtype: object
Dtype 轉換#
這是最低公共分母的上轉型,意味著你將獲得能夠容納所有型別的 dtype。
In [10]: df3.values.dtype
Out[10]: dtype('float64')
轉換
In [11]: df3.astype('float32').dtypes
Out[11]:
A float32
B float32
C float32
dtype: object
混合轉換
In [12]: df3['D'] = '1.'
In [13]: df3['E'] = '1'
In [14]: df3.convert_objects(convert_numeric=True).dtypes
Out[14]:
A float32
B float64
C float64
D float64
E int64
dtype: object
# same, but specific dtype conversion
In [15]: df3['D'] = df3['D'].astype('float16')
In [16]: df3['E'] = df3['E'].astype('int32')
In [17]: df3.dtypes
Out[17]:
A float32
B float64
C float64
D float16
E int32
dtype: object
強制日期轉換(當不是日期型別時設定為 NaT)
In [18]: import datetime
In [19]: s = pd.Series([datetime.datetime(2001, 1, 1, 0, 0), 'foo', 1.0, 1,
....: pd.Timestamp('20010104'), '20010105'], dtype='O')
....:
In [20]: s.convert_objects(convert_dates='coerce')
Out[20]:
0 2001-01-01
1 NaT
2 NaT
3 NaT
4 2001-01-04
5 2001-01-05
dtype: datetime64[ns]
Dtype 注意事項#
平臺注意事項
從 0.11.0 版本開始,DataFrame/Series 的構造將使用預設的 int64 和 float64 dtype,無論平臺如何。這與 pandas 的早期版本沒有明顯變化。但是,如果你指定了 dtype,它們*將會*被尊重(GH 2837)。
以下所有操作都將得到 int64 dtype。
In [21]: pd.DataFrame([1, 2], columns=['a']).dtypes
Out[21]:
a int64
dtype: object
In [22]: pd.DataFrame({'a': [1, 2]}).dtypes
Out[22]:
a int64
dtype: object
In [23]: pd.DataFrame({'a': 1}, index=range(2)).dtypes
Out[23]:
a int64
dtype: object
請記住,DataFrame(np.array([1,2])) 在 32 位平臺上*會*生成 int32!
上轉型注意事項
對整數型別資料執行索引操作很容易導致資料上轉型。在不引入 nan 的情況下,將保留輸入資料的 dtype。
In [24]: dfi = df3.astype('int32')
In [25]: dfi['D'] = dfi['D'].astype('int64')
In [26]: dfi
Out[26]:
A B C D E
0 0 0 0 1 1
1 -2 0 1 1 1
2 -2 0 2 1 1
3 0 -1 3 1 1
4 1 0 4 1 1
5 0 0 5 1 1
6 0 -1 6 1 1
7 0 0 7 1 1
In [27]: dfi.dtypes
Out[27]:
A int32
B int32
C int32
D int64
E int32
dtype: object
In [28]: casted = dfi[dfi > 0]
In [29]: casted
Out[29]:
A B C D E
0 NaN NaN NaN 1 1
1 NaN NaN 1.0 1 1
2 NaN NaN 2.0 1 1
3 NaN NaN 3.0 1 1
4 1.0 NaN 4.0 1 1
5 NaN NaN 5.0 1 1
6 NaN NaN 6.0 1 1
7 NaN NaN 7.0 1 1
In [30]: casted.dtypes
Out[30]:
A float64
B float64
C float64
D int64
E int32
dtype: object
而 float dtypes 則保持不變。
In [31]: df4 = df3.copy()
In [32]: df4['A'] = df4['A'].astype('float32')
In [33]: df4.dtypes
Out[33]:
A float32
B float64
C float64
D float16
E int32
dtype: object
In [34]: casted = df4[df4 > 0]
In [35]: casted
Out[35]:
A B C D E
0 NaN NaN NaN 1.0 1
1 NaN 0.567020 1.0 1.0 1
2 NaN 0.276232 2.0 1.0 1
3 NaN NaN 3.0 1.0 1
4 1.933792 NaN 4.0 1.0 1
5 NaN 0.113648 5.0 1.0 1
6 NaN NaN 6.0 1.0 1
7 NaN 0.524988 7.0 1.0 1
In [36]: casted.dtypes
Out[36]:
A float32
B float64
C float64
D float16
E int32
dtype: object
日期時間轉換#
DataFrame(或 Series)中的 Datetime64[ns] 列允許使用 np.nan 來表示 nan 值,除了傳統的 NaT,或 not-a-time。這允許以通用方式方便地設定 nan。此外,當傳遞日期時間類物件時,預設情況下會建立 datetime64[ns] 列(此更改是在 0.10.1 版本引入的)(GH 2809,GH 2810)。
In [12]: df = pd.DataFrame(np.random.randn(6, 2), pd.date_range('20010102', periods=6),
....: columns=['A', ' B'])
....:
In [13]: df['timestamp'] = pd.Timestamp('20010103')
In [14]: df
Out[14]:
A B timestamp
2001-01-02 0.404705 0.577046 2001-01-03
2001-01-03 -1.715002 -1.039268 2001-01-03
2001-01-04 -0.370647 -1.157892 2001-01-03
2001-01-05 -1.344312 0.844885 2001-01-03
2001-01-06 1.075770 -0.109050 2001-01-03
2001-01-07 1.643563 -1.469388 2001-01-03
# datetime64[ns] out of the box
In [15]: df.dtypes.value_counts()
Out[15]:
float64 2
datetime64[us] 1
Name: count, dtype: int64
# use the traditional nan, which is mapped to NaT internally
In [16]: df.loc[df.index[2:4], ['A', 'timestamp']] = np.nan
In [17]: df
Out[17]:
A B timestamp
2001-01-02 0.404705 0.577046 2001-01-03
2001-01-03 -1.715002 -1.039268 2001-01-03
2001-01-04 NaN -1.157892 NaT
2001-01-05 NaN 0.844885 NaT
2001-01-06 1.075770 -0.109050 2001-01-03
2001-01-07 1.643563 -1.469388 2001-01-03
將 datetime64[ns] 轉換為 object 時,`astype` 轉換會將 NaT 隱式轉換為 np.nan。
In [18]: import datetime
In [19]: s = pd.Series([datetime.datetime(2001, 1, 2, 0, 0) for i in range(3)])
In [20]: s.dtype
Out[20]: dtype('<M8[us]')
In [21]: s[1] = np.nan
In [22]: s
Out[22]:
0 2001-01-02
1 NaT
2 2001-01-02
dtype: datetime64[us]
In [23]: s.dtype
Out[23]: dtype('<M8[us]')
In [24]: s = s.astype('O')
In [25]: s
Out[25]:
0 2001-01-02 00:00:00
1 NaT
2 2001-01-02 00:00:00
dtype: object
In [26]: s.dtype
Out[26]: dtype('O')
API 更改#
向索引添加了 to_series() 方法,以方便建立索引器(GH 3275)。
HDFStore
為表添加了
select_column方法,以便從表中選擇單個列作為 Series。棄用了
unique方法,可以透過select_column(key,column).unique()來複制。
append的min_itemsize引數現在將自動為傳遞的鍵建立 data_columns。
增強功能#
df.to_csv() 的效能在某些情況下提高了高達 10 倍。(GH 3059)。
Numexpr 現在是推薦的依賴項,用於加速某些型別的數值和布林運算。
Bottleneck 現在是推薦的依賴項,用於加速某些型別的
nan運算。
HDFStore
支援
read_hdf/to_hdfAPI,類似於read_csv/to_csv。In [27]: df = pd.DataFrame({'A': range(5), 'B': range(5)}) In [28]: df.to_hdf('store.h5', key='table', append=True) In [29]: pd.read_hdf('store.h5', 'table', where=['index > 2']) Out[29]: A B 3 3 3 4 4 4為 store 的
get提供點屬性訪問,例如store.df == store['df']。提供了新的關鍵字
iterator=boolean和chunksize=number_in_a_chunk,以支援在select和select_as_multiple上進行迭代(GH 3076)。現在可以像處理有序時間序列一樣,從無序時間序列中選擇時間戳(GH 2437)。
現在可以透過字串從具有日期型索引的 DataFrame 中進行選擇,方式類似於 Series(GH 3070)。
In [30]: idx = pd.date_range("2001-10-1", periods=5, freq='M') In [31]: ts = pd.Series(np.random.rand(len(idx)), index=idx) In [32]: ts['2001'] Out[32]: 2001-10-31 0.117967 2001-11-30 0.702184 2001-12-31 0.414034 Freq: M, dtype: float64 In [33]: df = pd.DataFrame({'A': ts}) In [34]: df['2001'] Out[34]: A 2001-10-31 0.117967 2001-11-30 0.702184 2001-12-31 0.414034
Squeeze可能會移除物件中長度為 1 的維度。>>> p = pd.Panel(np.random.randn(3, 4, 4), items=['ItemA', 'ItemB', 'ItemC'], ... major_axis=pd.date_range('20010102', periods=4), ... minor_axis=['A', 'B', 'C', 'D']) >>> p <class 'pandas.core.panel.Panel'> Dimensions: 3 (items) x 4 (major_axis) x 4 (minor_axis) Items axis: ItemA to ItemC Major_axis axis: 2001-01-02 00:00:00 to 2001-01-05 00:00:00 Minor_axis axis: A to D >>> p.reindex(items=['ItemA']).squeeze() A B C D 2001-01-02 0.926089 -2.026458 0.501277 -0.204683 2001-01-03 -0.076524 1.081161 1.141361 0.479243 2001-01-04 0.641817 -0.185352 1.824568 0.809152 2001-01-05 0.575237 0.669934 1.398014 -0.399338 >>> p.reindex(items=['ItemA'], minor=['B']).squeeze() 2001-01-02 -2.026458 2001-01-03 1.081161 2001-01-04 -0.185352 2001-01-05 0.669934 Freq: D, Name: B, dtype: float64在
pd.io.data.Options中,
修復了嘗試獲取當月資料但已過期的錯誤。
現在使用 lxml 解析 html 而不是 BeautifulSoup(lxml 更快)。
當呼叫建立它們的方法時,新的 calls 和 puts 例項變數會被自動建立。這適用於當月,此時例項變數為
calls和puts。對於未來的到期月份也同樣適用,並將例項變數儲存為callsMMYY或putsMMYY,其中MMYY分別是期權的到期月份和年份。
Options.get_near_stock_price現在允許使用者指定獲取相關期權資料的月份。
Options.get_forward_data現在具有可選的 kwargsnear和above_below。這允許使用者指定是否僅返回接近當前股票價格的期權的前瞻性資料。這只是從 Options.get_near_stock_price 而不是 Options.get_xxx_data() 中獲取資料(GH 2758)。現在在時間序列圖中顯示游標座標資訊。
添加了選項
display.max_seq_items,用於控制列印序列時每個序列顯示的元素數量(GH 2979)。添加了選項
display.chop_threshold,用於控制顯示小數值(GH 2739)。添加了選項
display.max_info_rows,以防止為行數超過 100 萬的框架計算 verbose_info(可配置)(GH 2807,GH 2918)。value_counts() 現在接受一個“normalize”引數,用於標準化直方圖(GH 2710)。
DataFrame.from_records 現在不僅接受 dicts,還接受 collections.Mapping ABC 的任何例項。
添加了選項
display.mpl_style,為 plots 提供更時尚的視覺風格。基於 https://gist.github.com/huyng/816622(GH 3075)。將布林值視為整數(值為 1 和 0)進行數值運算(GH 2641)。
to_html() 現在接受一個可選的“escape”引數來控制保留 HTML 字元的轉義(預設啟用),除了
<和>之外,還會轉義&(GH 2919)。
請參閱 完整的釋出說明 或 GitHub 上的問題跟蹤器以獲取完整列表。
貢獻者#
共有 50 人為本次釋出貢獻了補丁。名字旁帶有“+”號的人是首次貢獻補丁。
Adam Greenhall +
Alvaro Tejero-Cantero +
Andy Hayden
Brad Buran +
Chang She
Chapman Siu +
Chris Withers +
Christian Geier +
Christopher Whelan
Damien Garaud
Dan Birken
Dan Davison +
Dieter Vandenbussche
Dražen Lučanin +
Dražen Lučanin +
Garrett Drapala
Illia Polosukhin +
James Casbon +
Jeff Reback
Jeremy Wagner +
Jonathan Chambers +
K.-Michael Aye
Karmel Allison +
Loïc Estève +
Nicholaus E. Halecky +
Peter Prettenhofer +
Phillip Cloud +
Robert Gieseke +
Skipper Seabold
Spencer Lyon
Stephen Lin +
Thierry Moisan +
Thomas Kluyver
Tim Akinbo +
Vytautas Jancauskas
Vytautas Jančauskas +
Wes McKinney
Will Furnass +
Wouter Overmeire
anomrake +
davidjameshumphreys +
dengemann +
dieterv77 +
jreback
lexual +
stephenwlin +
thauck +
vytas +
waitingkuo +
y-p