版本 0.13.1 (2014 年 2 月 3 日)#

這是相對於 0.13.0 的次要版本釋出,包含少量 API 更改、若干新功能、增強功能和效能改進,以及大量的錯誤修復。我們建議所有使用者升級到此版本。

亮點包括

  • read_csv/to_datetime 添加了 infer_datetime_format 關鍵字,以加速同構格式的日期時間解析。

  • 將智慧地限制日期時間/時間差格式的顯示精度。

  • 增強了 Panel 的 apply() 方法。

  • 在新的 教程 部分推薦了教程。

  • 我們的 pandas 生態系統正在不斷壯大,我們現在在新 生態系統頁面 部分展示相關專案。

  • 在改進文件方面做了大量工作,並添加了一個新的 貢獻 部分。

  • 即使它可能只對開發者感興趣,我們也 <3>我們新的 CI 狀態頁面:ScatterCI

警告

0.13.1 修復了一個由 numpy < 1.8 和對類字串陣列進行鏈式賦值的組合引起的錯誤。鏈式索引可能會產生意外結果,通常應避免使用。

這之前會導致段錯誤

df = pd.DataFrame({"A": np.array(["foo", "bar", "bah", "foo", "bar"])})
df["A"].iloc[0] = np.nan

執行此類賦值的推薦方法是

In [1]: df = pd.DataFrame({"A": np.array(["foo", "bar", "bah", "foo", "bar"])})

In [2]: df.loc[0, "A"] = np.nan

In [3]: df
Out[3]: 
     A
0  NaN
1  bar
2  bah
3  foo
4  bar

輸出格式增強#

  • df.info() 檢視現在顯示每列的 dtype 資訊(GH 5682

  • df.info() 現在遵守 max_info_rows 選項,以停用大型資料幀的空值計數(GH 5974

    In [4]: max_info_rows = pd.get_option("max_info_rows")
    
    In [5]: df = pd.DataFrame(
       ...:     {
       ...:         "A": np.random.randn(10),
       ...:         "B": np.random.randn(10),
       ...:         "C": pd.date_range("20130101", periods=10),
       ...:     }
       ...: )
       ...: 
    
    In [6]: df.iloc[3:6, [0, 2]] = np.nan
    
    # set to not display the null counts
    In [7]: pd.set_option("max_info_rows", 0)
    
    In [8]: df.info()
    <class 'pandas.DataFrame'>
    RangeIndex: 10 entries, 0 to 9
    Data columns (total 3 columns):
     #   Column  Dtype         
    ---  ------  -----         
     0   A       float64       
     1   B       float64       
     2   C       datetime64[us]
    dtypes: datetime64[us](1), float64(2)
    memory usage: 372.0 bytes
    
    # this is the default (same as in 0.13.0)
    In [9]: pd.set_option("max_info_rows", max_info_rows)
    
    In [10]: df.info()
    <class 'pandas.DataFrame'>
    RangeIndex: 10 entries, 0 to 9
    Data columns (total 3 columns):
     #   Column  Non-Null Count  Dtype         
    ---  ------  --------------  -----         
     0   A       7 non-null      float64       
     1   B       10 non-null     float64       
     2   C       7 non-null      datetime64[us]
    dtypes: datetime64[us](1), float64(2)
    memory usage: 372.0 bytes
    
  • 為新的 DataFrame repr 添加了 show_dimensions 顯示選項,以控制是否列印維度。

    In [11]: df = pd.DataFrame([[1, 2], [3, 4]])
    
    In [12]: pd.set_option("show_dimensions", False)
    
    In [13]: df
    Out[13]: 
       0  1
    0  1  2
    1  3  4
    
    In [14]: pd.set_option("show_dimensions", True)
    
    In [15]: df
    Out[15]: 
       0  1
    0  1  2
    1  3  4
    
    [2 rows x 2 columns]
    
  • 用於 datetimetimedelta64ArrayFormatter 現在可以根據陣列中的值智慧地限制精度(GH 3401

    以前的輸出可能看起來像

      age                 today               diff
    0 2001-01-01 00:00:00 2013-04-19 00:00:00 4491 days, 00:00:00
    1 2004-06-01 00:00:00 2013-04-19 00:00:00 3244 days, 00:00:00
    

    現在的輸出看起來像

    In [16]: df = pd.DataFrame(
       ....:     [pd.Timestamp("20010101"), pd.Timestamp("20040601")], columns=["age"]
       ....: )
       ....: 
    
    In [17]: df["today"] = pd.Timestamp("20130419")
    
    In [18]: df["diff"] = df["today"] - df["age"]
    
    In [19]: df
    Out[19]: 
             age      today      diff
    0 2001-01-01 2013-04-19 4491 days
    1 2004-06-01 2013-04-19 3244 days
    
    [2 rows x 3 columns]
    

API 更改#

  • -NaN-nan 新增到預設的 NA 值集中(GH 5952)。請參閱 NA 值

  • 添加了 Series.str.get_dummies 向量化字串方法(GH 6021),用於提取分隔字串列的虛擬/指示變數

    In [20]: s = pd.Series(["a", "a|b", np.nan, "a|c"])
    
    In [21]: s.str.get_dummies(sep="|")
    Out[21]: 
       a  b  c
    0  1  0  0
    1  1  1  0
    2  0  0  0
    3  1  0  1
    
    [4 rows x 3 columns]
    
  • 添加了 NDFrame.equals() 方法來比較兩個 NDFrames 是否相等,具有相等的軸、dtype 和值。添加了 array_equivalent 函式來比較兩個 ndarrays 是否相等。相同位置的 NaN 被視為相等。(GH 5283)另請參閱 文件 以獲取動機示例。

    df = pd.DataFrame({"col": ["foo", 0, np.nan]})
    df2 = pd.DataFrame({"col": [np.nan, 0, "foo"]}, index=[2, 1, 0])
    df.equals(df2)
    df.equals(df2.sort_index())
    
  • DataFrame.apply 將使用 reduce 引數來確定當 DataFrame 為空時,是返回 Series 還是 DataFrameGH 6007)。

    以前,對空 DataFrame 呼叫 DataFrame.apply 會返回一個 DataFrame(如果沒有列),或者傳遞給函式的函式將使用一個空的 Series 來猜測是返回 Series 還是 DataFrame

    In [32]: def applied_func(col):
      ....:    print("Apply function being called with: ", col)
      ....:    return col.sum()
      ....:
    
    In [33]: empty = DataFrame(columns=['a', 'b'])
    
    In [34]: empty.apply(applied_func)
    Apply function being called with:  Series([], Length: 0, dtype: float64)
    Out[34]:
    a   NaN
    b   NaN
    Length: 2, dtype: float64
    

    現在,當 apply 在空 DataFrame 上呼叫時:如果 reduce 引數為 True,則返回 Series;如果為 False,則返回 DataFrame;如果為 None(預設值),則將使用一個空的 Series 呼叫要應用的函式,以嘗試猜測返回型別。

    In [35]: empty.apply(applied_func, reduce=True)
    Out[35]:
    a   NaN
    b   NaN
    Length: 2, dtype: float64
    
    In [36]: empty.apply(applied_func, reduce=False)
    Out[36]:
    Empty DataFrame
    Columns: [a, b]
    Index: []
    
    [0 rows x 2 columns]
    

先前版本的棄用/更改#

0.13 或更早版本中沒有宣佈的更改將在 0.13.1 中生效

棄用#

0.13.1 中沒有對先前行為的棄用

增強功能#

  • pd.read_csvpd.to_datetime 學習了一個新的 infer_datetime_format 關鍵字,在許多情況下極大地提高了解析效能。感謝 @lexual 的建議和 @danbirken 的快速實現。(GH 5490GH 6021

    如果啟用了 parse_dates 並且設定了此標誌,pandas 將嘗試推斷列中日期時間字串的格式,如果可以推斷,則切換到更快的解析方法。在某些情況下,這可以將解析速度提高約 5-10 倍。

    # Try to infer the format for the index column
    df = pd.read_csv(
        "foo.csv", index_col=0, parse_dates=True, infer_datetime_format=True
    )
    
  • 在寫入 excel 檔案時,現在可以指定 date_formatdatetime_format 關鍵字(GH 4133

  • 用於從一組可迭代物件的笛卡爾積建立 MultiIndex 的 MultiIndex.from_product 便利函式(GH 6055

    In [22]: shades = ["light", "dark"]
    
    In [23]: colors = ["red", "green", "blue"]
    
    In [24]: pd.MultiIndex.from_product([shades, colors], names=["shade", "color"])
    Out[24]: 
    MultiIndex([('light',   'red'),
                ('light', 'green'),
                ('light',  'blue'),
                ( 'dark',   'red'),
                ( 'dark', 'green'),
                ( 'dark',  'blue')],
               names=['shade', 'color'])
    
  • Panel 的 apply() 將適用於非 ufuncs。請參閱 文件

    In [28]: import pandas._testing as tm
    
    In [29]: panel = tm.makePanel(5)
    
    In [30]: panel
    Out[30]:
    <class 'pandas.core.panel.Panel'>
    Dimensions: 3 (items) x 5 (major_axis) x 4 (minor_axis)
    Items axis: ItemA to ItemC
    Major_axis axis: 2000-01-03 00:00:00 to 2000-01-07 00:00:00
    Minor_axis axis: A to D
    
    In [31]: panel['ItemA']
    Out[31]:
                       A         B         C         D
    2000-01-03 -0.673690  0.577046 -1.344312 -1.469388
    2000-01-04  0.113648 -1.715002  0.844885  0.357021
    2000-01-05 -1.478427 -1.039268  1.075770 -0.674600
    2000-01-06  0.524988 -0.370647 -0.109050 -1.776904
    2000-01-07  0.404705 -1.157892  1.643563 -0.968914
    
    [5 rows x 4 columns]
    

    指定一個作用於 Series(返回單個元素)的 apply

    In [32]: panel.apply(lambda x: x.dtype, axis='items')
    Out[32]:
                      A        B        C        D
    2000-01-03  float64  float64  float64  float64
    2000-01-04  float64  float64  float64  float64
    2000-01-05  float64  float64  float64  float64
    2000-01-06  float64  float64  float64  float64
    2000-01-07  float64  float64  float64  float64
    
    [5 rows x 4 columns]
    

    類似的歸約型別操作

    In [33]: panel.apply(lambda x: x.sum(), axis='major_axis')
    Out[33]:
          ItemA     ItemB     ItemC
    A -1.108775 -1.090118 -2.984435
    B -3.705764  0.409204  1.866240
    C  2.110856  2.960500 -0.974967
    D -4.532785  0.303202 -3.685193
    
    [4 rows x 3 columns]
    

    這相當於

    In [34]: panel.sum('major_axis')
    Out[34]:
          ItemA     ItemB     ItemC
    A -1.108775 -1.090118 -2.984435
    B -3.705764  0.409204  1.866240
    C  2.110856  2.960500 -0.974967
    D -4.532785  0.303202 -3.685193
    
    [4 rows x 3 columns]
    

    一個返回 Panel 的轉換操作,但它正在跨 major_axis 計算 z 分數

    In [35]: result = panel.apply(lambda x: (x - x.mean()) / x.std(),
      ....:                      axis='major_axis')
      ....:
    
    In [36]: result
    Out[36]:
    <class 'pandas.core.panel.Panel'>
    Dimensions: 3 (items) x 5 (major_axis) x 4 (minor_axis)
    Items axis: ItemA to ItemC
    Major_axis axis: 2000-01-03 00:00:00 to 2000-01-07 00:00:00
    Minor_axis axis: A to D
    
    In [37]: result['ItemA']                           # noqa E999
    Out[37]:
                      A         B         C         D
    2000-01-03 -0.535778  1.500802 -1.506416 -0.681456
    2000-01-04  0.397628 -1.108752  0.360481  1.529895
    2000-01-05 -1.489811 -0.339412  0.557374  0.280845
    2000-01-06  0.885279  0.421830 -0.453013 -1.053785
    2000-01-07  0.742682 -0.474468  1.041575 -0.075499
    
    [5 rows x 4 columns]
    
  • Panel 的 apply() 作用於橫截面切片。(GH 1148

    In [38]: def f(x):
       ....:     return ((x.T - x.mean(1)) / x.std(1)).T
       ....:
    
    In [39]: result = panel.apply(f, axis=['items', 'major_axis'])
    
    In [40]: result
    Out[40]:
    <class 'pandas.core.panel.Panel'>
    Dimensions: 4 (items) x 5 (major_axis) x 3 (minor_axis)
    Items axis: A to D
    Major_axis axis: 2000-01-03 00:00:00 to 2000-01-07 00:00:00
    Minor_axis axis: ItemA to ItemC
    
    In [41]: result.loc[:, :, 'ItemA']
    Out[41]:
                       A         B         C         D
    2000-01-03  0.012922 -0.030874 -0.629546 -0.757034
    2000-01-04  0.392053 -1.071665  0.163228  0.548188
    2000-01-05 -1.093650 -0.640898  0.385734 -1.154310
    2000-01-06  1.005446 -1.154593 -0.595615 -0.809185
    2000-01-07  0.783051 -0.198053  0.919339 -1.052721
    
    [5 rows x 4 columns]
    

    這相當於以下內容

    In [42]: result = pd.Panel({ax: f(panel.loc[:, :, ax]) for ax in panel.minor_axis})
    
    In [43]: result
    Out[43]:
    <class 'pandas.core.panel.Panel'>
    Dimensions: 4 (items) x 5 (major_axis) x 3 (minor_axis)
    Items axis: A to D
    Major_axis axis: 2000-01-03 00:00:00 to 2000-01-07 00:00:00
    Minor_axis axis: ItemA to ItemC
    
    In [44]: result.loc[:, :, 'ItemA']
    Out[44]:
                       A         B         C         D
    2000-01-03  0.012922 -0.030874 -0.629546 -0.757034
    2000-01-04  0.392053 -1.071665  0.163228  0.548188
    2000-01-05 -1.093650 -0.640898  0.385734 -1.154310
    2000-01-06  1.005446 -1.154593 -0.595615 -0.809185
    2000-01-07  0.783051 -0.198053  0.919339 -1.052721
    
    [5 rows x 4 columns]
    

效能#

0.13.1 的效能改進

  • Series 日期時間/時間差二元運算(GH 5801

  • DataFrame 的 count/dropna 針對 axis=1

  • Series.str.contains 現在有一個 regex=False 關鍵字,對於純(非正則表示式)字串模式,它可以更快。(GH 5879

  • Series.str.extract(GH 5944

  • dtypes/ftypes 方法(GH 5968

  • 使用 object dtypes 進行索引(GH 5968

  • DataFrame.applyGH 6013

  • JSON IO 中的迴歸(GH 5765

  • 從 Series 構建索引(GH 6150

實驗性#

0.13.1 中沒有實驗性更改

Bug 修復#

  • io.wb.get_countries 中的錯誤未包含所有國家(GH 6008

  • Series replace 使用時間戳字典中的錯誤(GH 5797

  • read_csv/read_table 現在尊重 prefix kwarg(GH 5732)。

  • 透過 .ix 從重複索引的 DataFrame 進行選擇時包含缺失值的錯誤失敗(GH 5835

  • 修復了空 DataFrame 上布林比較的錯誤(GH 5808

  • isnull 處理物件陣列中 NaT 的錯誤(GH 5443

  • 當傳遞 np.nan 或整數日期型別和格式字串時,to_datetime 中的錯誤(GH 5863

  • groupby Dtype 轉換與日期時間型別相關的錯誤(GH 5869

  • 空 Series 作為 Indexer 到 Series 的處理迴歸(GH 5877

  • 內部快取錯誤,與(GH 5727)相關

  • 在 py3 下,在 windows 上從非檔案路徑讀取 JSON/msgpack 的測試錯誤(GH 5874

  • 當使用 .ix[tuple(…)] 進行賦值時出錯(GH 5896

  • 完全重新索引 Panel 時出錯(GH 5905

  • idxmin/max 處理 object dtypes 時出錯(GH 5914

  • BusinessDay 在向非偏移日期新增 n 天時出錯,其中 n>5 且 n%5==0(GH 5890

  • 透過 ix 將鏈式 Series 分配給 Series 時出錯(GH 5928

  • 建立空 DataFrame、複製然後賦值時出錯(GH 5932

  • DataFrame.tail 處理空幀時出錯(GH 5846

  • resample 時元資料傳播錯誤(GH 5862

  • 修復了 NaT 的字串表示形式為“NaT”(GH 5708

  • 修復了 Timestamp 的字串表示形式,如果存在納秒則顯示納秒(GH 5912

  • pd.match 未返回傳入的哨兵

  • Panel.to_frame()major_axisMultiIndex 時不再失敗(GH 5402)。

  • pd.read_msgpack 在錯誤地推斷 DateTimeIndex 頻率時出錯(GH 5947

  • 修復了 to_datetime 處理同時包含時區感知的日期時間和 NaT 的陣列的錯誤(GH 5961

  • 滾動 skew/kurtosis 方法在傳遞帶有錯誤資料的 Series 時出錯(GH 5749

  • scipy interpolate 方法處理日期時間索引時出錯(GH 5975

  • 當傳遞混合的 datetime/np.datetime64 和 NaT 時,NaT 比較錯誤(GH 5968

  • 修復了 pd.concat 在所有輸入為空時丟失 Dtype 資訊的錯誤(GH 5742

  • IPython 的近期更改導致在使用舊版本 pandas 在 QTConsole 中時發出警告,現已修復。如果您使用的是舊版本且需要抑制警告,請參閱(GH 5922)。

  • 合併 timedelta Dtypes 時出錯(GH 5695

  • plotting.scatter_matrix 函式中的錯誤。對角線和非對角線圖之間的對齊不正確,請參閱(GH 5497)。

  • 透過 ix 訪問帶有 MultiIndex 的 Series 時迴歸(GH 6018

  • Series.xs 使用 MultiIndex 時出錯(GH 6018

  • 建立混合型別 Series 時出錯,其中包含日期型別和整數(應產生 object 型別,而不是自動轉換)(GH 6028

  • 在 NumPy 1.7.1 下使用物件陣列進行鏈式索引時可能發生段錯誤(GH 6026GH 6056

  • 使用花式索引將單個元素設定為非標量(例如列表)時出錯(GH 6043

  • to_sql 未遵循 if_existsGH 4110 GH 4304

  • 從 0.12 開始的 .get(None) 索引迴歸(GH 5652

  • 微妙的 iloc 索引錯誤,在(GH 6059)中暴露

  • 將字串插入 DatetimeIndex 時出錯(GH 5818

  • 修復了 to_html/HTML repr 中的 Unicode 錯誤(GH 6098

  • 修復了 get_options_data 中的缺失引數驗證(GH 6105

  • 當具有重複列的 DataFrame 中的位置是切片(例如相鄰)時,賦值時出錯(GH 6120

  • 在具有重複索引/列的 DataFrame 構建期間傳播 _ref_locs 時出錯(GH 6121

  • DataFrame.apply 在使用混合日期型別歸約時出錯(GH 6125

  • DataFrame.append 在追加具有不同列的行時出錯(GH 6129

  • 使用 recarray 和非 ns 日期時間 dtype 構建 DataFrame 時出錯(GH 6140

  • .loc setitem 索引,其中右側為 dataframe,進行多項設定,且是日期時間型別(GH 6152

  • 修復了 query/eval 在進行詞典字串比較時的錯誤(GH 6155)。

  • 修復了 query 中單元素 Series 的索引被丟棄的錯誤(GH 6148)。

  • 在將具有 MultiIndexed 列的 DataFrame 追加到現有表時,HDFStore 出錯(GH 6167

  • 在設定空 DataFrame 時 Dtypes 的一致性(GH 6171

  • HDFStore 上對 MultiIndex 進行選擇時出錯,即使存在未充分指定的列規範(GH 6169

  • nanops.varddof=1 和 1 個元素時,在某些平臺上有時會返回 inf 而不是 nanGH 6136

  • Series 和 DataFrame 的條形圖圖表忽略 use_index 關鍵字時出錯(GH 6209

  • 修復了 python3 下 groupby 混合 str/int 的錯誤;argsort 失敗了(GH 6212

貢獻者#

共有 52 人為本次釋出貢獻了補丁。“+”號表示首次貢獻補丁。

  • Alex Rothberg

  • Alok Singhal +

  • Andrew Burrows +

  • Andy Hayden

  • Bjorn Arneson +

  • Brad Buran

  • Caleb Epstein

  • Chapman Siu

  • Chase Albert +

  • Clark Fitzgerald +

  • DSM

  • Dan Birken

  • Daniel Waeber +

  • David Wolever +

  • Doran Deluz +

  • Douglas McNeil +

  • Douglas Rudd +

  • Dražen Lučanin

  • Elliot S +

  • Felix Lawrence +

  • George Kuan +

  • Guillaume Gay +

  • Jacob Schaer

  • Jan Wagner +

  • Jeff Tratner

  • John McNamara

  • Joris Van den Bossche

  • Julia Evans +

  • Kieran O’Mahony

  • Michael Schatzow +

  • Naveen Michaud-Agrawal +

  • Patrick O’Keeffe +

  • Phillip Cloud

  • Roman Pekar

  • Skipper Seabold

  • Spencer Lyon

  • Tom Augspurger +

  • TomAugspurger

  • acorbe +

  • akittredge +

  • bmu +

  • bwignall +

  • chapman siu

  • danielballan

  • david +

  • davidshinn

  • immerrr +

  • jreback

  • lexual

  • mwaskom +

  • unutbu

  • y-p