版本0.12.0(2013年7月24日)#

这是从0.11.0开始的一个主要版本,包括几个新功能和增强功能,以及大量的错误修复。

亮点包括一致的I/O API命名方案、读取html的例程、将多索引写入CSV文件、读写Stata数据文件、读写JSON格式文件、支持 HDFStore ,通过筛选GROUP BY表达式 filter ,以及改装后的 replace 接受正则表达式的例程。

API更改#

  • I/O API现在与一组顶层 reader 访问的功能如下 pd.read_csv() ,它通常返回一个 pandas 对象。

    • read_csv

    • read_excel

    • read_hdf

    • read_sql

    • read_json

    • read_html

    • read_stata

    • read_clipboard

    相应的 writer 函数是对象方法,其访问方式如下 df.to_csv()

    • to_csv

    • to_excel

    • to_hdf

    • to_sql

    • to_json

    • to_html

    • to_stata

    • to_clipboard

  • 修复Series、DataFrames上的模除法和整数除法,以类似于 float 要返回的数据类型 np.nannp.inf 视情况而定 (GH3590 )。这纠正了一个麻木的错误, integerfloat 数据类型不同。

    In [1]: p = pd.DataFrame({"first": [4, 5, 8], "second": [0, 0, 3]})
    
    In [2]: p % 0
    Out[2]: 
       first  second
    0    NaN     NaN
    1    NaN     NaN
    2    NaN     NaN
    
    In [3]: p % p
    Out[3]: 
       first  second
    0    0.0     NaN
    1    0.0     NaN
    2    0.0     0.0
    
    In [4]: p / p
    Out[4]: 
       first  second
    0    1.0     NaN
    1    1.0     NaN
    2    1.0     1.0
    
    In [5]: p / 0
    Out[5]: 
       first  second
    0    inf     NaN
    1    inf     NaN
    2    inf     inf
    
  • 添加 squeeze 关键字至 groupby 如果组是唯一的,则允许从DataFrame->Series减少。这是从0.10.1开始的回归。我们又回到了以前的行为。这意味着,无论组是否唯一,Groupby都将返回相同形状的对象。恢复此问题 (GH2893 )与 (GH3596 )。

    In [2]: df2 = pd.DataFrame([{"val1": 1, "val2": 20},
       ...:                     {"val1": 1, "val2": 19},
       ...:                     {"val1": 1, "val2": 27},
       ...:                     {"val1": 1, "val2": 12}])
    
    In [3]: def func(dataf):
       ...:     return dataf["val2"] - dataf["val2"].mean()
       ...:
    
    In [4]: # squeezing the result frame to a series (because we have unique groups)
       ...: df2.groupby("val1", squeeze=True).apply(func)
    Out[4]:
    0    0.5
    1   -0.5
    2    7.5
    3   -7.5
    Name: 1, dtype: float64
    
    In [5]: # no squeezing (the default, and behavior in 0.10.1)
       ...: df2.groupby("val1").apply(func)
    Out[5]:
    val2    0    1    2    3
    val1
    1     0.5 -0.5  7.5 -7.5
    
  • 加薪开始 iloc 当使用基于标签的索引器掩码(例如布尔系列)进行布尔索引时,即使使用整数标签,也会引发。自.以来 iloc 是纯粹基于位置的,系列上的标签不可对齐 (GH3631 )

    这种情况很少使用,而且有很多替代方案。这保留了 iloc 空气污染指数待定 纯粹是 基于位置的。

    In [6]: df = pd.DataFrame(range(5), index=list("ABCDE"), columns=["a"])
    
    In [7]: mask = df.a % 2 == 0
    
    In [8]: mask
    Out[8]: 
    A     True
    B    False
    C     True
    D    False
    E     True
    Name: a, dtype: bool
    
    # this is what you should use
    In [9]: df.loc[mask]
    Out[9]: 
       a
    A  0
    C  2
    E  4
    
    # this will work as well
    In [10]: df.iloc[mask.values]
    Out[10]: 
       a
    A  0
    C  2
    E  4
    

    df.iloc[mask] will raise a ValueError

  • 这个 raise_on_error 删除绘图函数的参数。相反,绘图函数会引发 TypeErrordtype 对象的属性是 object 提醒你要避免 object 数组,因此,如果需要绘制某些内容,则应强制转换为适当的数字数据类型。

  • 添加 colormap DataFrame绘图方法的关键字。接受matplotlib色彩映射对象(即matplotlib.cm.jet)或此类对象的字符串名称(即‘JET’)。对色彩映射表进行采样以选择每列的颜色。请看 色彩映射图 了解更多信息。 (GH3860 )

  • DataFrame.interpolate() 现在已弃用。请使用 DataFrame.fillna()DataFrame.replace() 取而代之的是。 (GH3582GH3675GH3676 )

  • 这个 methodaxis 的论据 DataFrame.replace() 已弃用

  • DataFrame.replace %s infer_types 参数已删除,现在默认情况下执行转换。 (GH3907 )

  • 添加关键字 allow_duplicatesDataFrame.insert 若要允许插入重复列,请执行以下操作 True ,默认为 False (与0.12之前相同) (GH3679 )

  • 实施 __nonzero__NDFrame 对象 (GH3691GH3696 )

  • IO API

    • 新增顶层功能 read_excel 为了替换以下内容,原始API已弃用,并将在未来的版本中删除

      from pandas.io.parsers import ExcelFile
      
      xls = ExcelFile("path_to_file.xls")
      xls.parse("Sheet1", index_col=None, na_values=["NA"])
      

      使用

      import pandas as pd
      
      pd.read_excel("path_to_file.xls", "Sheet1", index_col=None, na_values=["NA"])
      
    • 新增顶层功能 read_sql 这相当于以下内容

      from pandas.io.sql import read_frame
      
      read_frame(...)
      
  • DataFrame.to_htmlDataFrame.to_latex 现在接受他们的第一个论点的路径 (GH3702 )

  • Do not allow astypes on datetime64[ns] except to object, and timedelta64[ns] to object/int (GH3425)

  • 的行为 datetime64 对于某些所谓的约简操作,数据类型已更改 (GH3726 )。下面的操作现在引发 TypeError 当在一个 Series 并返回一个 空的 Series 当在一个 DataFrame 类似于对,例如, DataFrameslice 对象:

    • Sum、Prod、Mean、Std、Var、Skew、Kurt、Corr和Cover

  • read_html 现在默认为 None 在阅读时,靠在后面 bs4 + html5lib 当lxml无法解析时。要尝试的分析器列表,直到成功也有效为止

  • 内部 pandas 类层次结构已更改(略有更改)。上一次 PandasObject 现在被称为 PandasContainer 和一个新的 PandasObject 已成为 PandasContainer 以及 IndexCategoricalGroupBySparseList ,以及 SparseArray (+他们的基类)。目前, PandasObject 提供字符串方法(来自 StringMixin )。 (GH4090GH4092 )

  • 新的 StringMixin 这一点,给出了一个 __unicode__ 方法,获取与python2和python3兼容的字符串方法 (__str____bytes__ ,以及 __repr__ )。自始至终都有绳索安全。现在受雇于整个大Pandas类库的许多地方。 (GH4090GH4092 )

IO增强功能#

  • pd.read_html() can now parse HTML strings, files or urls and return DataFrames, courtesy of @cpcloud. (GH3477, GH3605, GH3606, GH3616). It works with a single parser backend: BeautifulSoup4 + html5lib See the docs

    您可以使用 pd.read_html() 从以下位置读取输出 DataFrame.to_html() 就像这样

    In [11]: df = pd.DataFrame({"a": range(3), "b": list("abc")})
    
    In [12]: print(df)
       a  b
    0  0  a
    1  1  b
    2  2  c
    
    In [13]: html = df.to_html()
    
    In [14]: alist = pd.read_html(html, index_col=0)
    
    In [15]: print(df == alist[0])
          a     b
    0  True  True
    1  True  True
    2  True  True
    

    请注意, alist 这是一条 Python list 所以 pd.read_html()DataFrame.to_html() 不是反转的。

    • pd.read_html() 不再执行日期字符串的硬转换 (GH3656 )。

    警告

    您可能需要安装较旧版本的BeautifulSoup4, See the installation docs

  • Added module for reading and writing Stata files: pandas.io.stata (GH1512) accessible via read_stata top-level function for reading, and to_stata DataFrame method for writing, See the docs

  • 新增json格式文件读写模块: pandas.io.json 可通过以下方式访问 read_json 顶层阅读功能,以及 to_json 用于写入的DataFrame方法, See the docs 各种问题 (GH1226GH3804GH3876GH3867GH1305 )

  • MultiIndex 用于读写CSV格式文件的列支持

    • 这个 header 选项输入 read_csv 现在接受要从中读取索引的行列表。

    • 这个选项, tupleize_cols 现在可以在两者中指定 to_csvread_csv ,为0.12之前的写入和读取行为提供兼容性 MultIndex 列通过元组列表。0.12中的默认设置是编写元组列表和 not 将元组列表解释为 MultiIndex 列。

      注意:0.12中的默认行为与以前的版本保持不变,但从默认的0.13开始 to 写入和读取 MultiIndex 列将采用新格式。 (GH3571GH1651GH3141 )

    • 如果一个 index_col 未指定(例如,您没有索引,或使用 df.to_csv(..., index=False ),然后任何 names 列上的索引将是 lost

      In [16]: from pandas._testing import makeCustomDataframe as mkdf
      
      In [17]: df = mkdf(5, 3, r_idx_nlevels=2, c_idx_nlevels=4)
      
      In [18]: df.to_csv("mi.csv")
      
      In [19]: print(open("mi.csv").read())
      C0,,C_l0_g0,C_l0_g1,C_l0_g2
      C1,,C_l1_g0,C_l1_g1,C_l1_g2
      C2,,C_l2_g0,C_l2_g1,C_l2_g2
      C3,,C_l3_g0,C_l3_g1,C_l3_g2
      R0,R1,,,
      R_l0_g0,R_l1_g0,R0C0,R0C1,R0C2
      R_l0_g1,R_l1_g1,R1C0,R1C1,R1C2
      R_l0_g2,R_l1_g2,R2C0,R2C1,R2C2
      R_l0_g3,R_l1_g3,R3C0,R3C1,R3C2
      R_l0_g4,R_l1_g4,R4C0,R4C1,R4C2
      
      
      In [20]: pd.read_csv("mi.csv", header=[0, 1, 2, 3], index_col=[0, 1])
      Out[20]: 
      C0              C_l0_g0 C_l0_g1 C_l0_g2
      C1              C_l1_g0 C_l1_g1 C_l1_g2
      C2              C_l2_g0 C_l2_g1 C_l2_g2
      C3              C_l3_g0 C_l3_g1 C_l3_g2
      R0      R1                             
      R_l0_g0 R_l1_g0    R0C0    R0C1    R0C2
      R_l0_g1 R_l1_g1    R1C0    R1C1    R1C2
      R_l0_g2 R_l1_g2    R2C0    R2C1    R2C2
      R_l0_g3 R_l1_g3    R3C0    R3C1    R3C2
      R_l0_g4 R_l1_g4    R4C0    R4C1    R4C2
      
  • 支持 HDFStore (通过 PyTables 3.0.0 )在Python3上

  • 迭代器支持通过 read_hdf 它会在迭代完成时自动打开和关闭存储区。这仅适用于 表格

    In [25]: path = 'store_iterator.h5'
    
    In [26]: pd.DataFrame(np.random.randn(10, 2)).to_hdf(path, 'df', table=True)
    
    In [27]: for df in pd.read_hdf(path, 'df', chunksize=3):
       ....:     print(df)
       ....:
              0         1
    0  0.713216 -0.778461
    1 -0.661062  0.862877
    2  0.344342  0.149565
              0         1
    3 -0.626968 -0.875772
    4 -0.930687 -0.218983
    5  0.949965 -0.442354
              0         1
    6 -0.402985  1.111358
    7 -0.241527 -0.670477
    8  0.049355  0.632633
              0         1
    9 -1.502767 -1.225492
    
  • read_csv 现在,当文件不包含任何列(例如,所有换行符)时,将抛出更具信息性的错误消息

其他增强功能#

  • DataFrame.replace() now allows regular expressions on contained Series with object dtype. See the examples section in the regular docs Replacing via String Expression

    例如,您可以这样做

    In [21]: df = pd.DataFrame({"a": list("ab.."), "b": [1, 2, 3, 4]})
    
    In [22]: df.replace(regex=r"\s*\.\s*", value=np.nan)
    Out[22]: 
         a  b
    0    a  1
    1    b  2
    2  NaN  3
    3  NaN  4
    

    替换字符串的所有匹配项 '.' 具有零个或多个周围空白的实例, NaN

    常规字符串替换仍能按预期工作。例如,您可以执行以下操作

    In [23]: df.replace(".", np.nan)
    Out[23]: 
         a  b
    0    a  1
    1    b  2
    2  NaN  3
    3  NaN  4
    

    替换字符串的所有匹配项 '.' 使用 NaN

  • pd.melt() 现在接受可选参数 var_namevalue_name 指定返回的DataFrame的自定义列名。

  • pd.set_option() 现在允许N个选项、值对 (GH3667 )。

    假设我们有一个选择 'a.b' 和另一种选择 'b.c' 。我们可以同时设置它们:

    In [31]: pd.get_option('a.b')
    Out[31]: 2
    
    In [32]: pd.get_option('b.c')
    Out[32]: 3
    
    In [33]: pd.set_option('a.b', 1, 'b.c', 4)
    
    In [34]: pd.get_option('a.b')
    Out[34]: 1
    
    In [35]: pd.get_option('b.c')
    Out[35]: 4
    
  • 这个 filter 方法返回原始对象的子集。假设我们只想获取属于组和大于2的组的元素。

    In [24]: sf = pd.Series([1, 1, 2, 3, 3, 3])
    
    In [25]: sf.groupby(sf).filter(lambda x: x.sum() > 2)
    Out[25]: 
    3    3
    4    3
    5    3
    dtype: int64
    

    的论据 filter 必须是一个函数,该函数作为一个整体应用于组并返回 TrueFalse

    另一个有用的操作是筛选出属于只有几个成员的组的元素。

    In [26]: dff = pd.DataFrame({"A": np.arange(8), "B": list("aabbbbcc")})
    
    In [27]: dff.groupby("B").filter(lambda x: len(x) > 2)
    Out[27]: 
       A  B
    2  2  b
    3  3  b
    4  4  b
    5  5  b
    

    或者,我们可以返回一个类似索引的对象,其中未通过筛选器的组由NAN填充,而不是删除违规的组。

    In [28]: dff.groupby("B").filter(lambda x: len(x) > 2, dropna=False)
    Out[28]: 
         A    B
    0  NaN  NaN
    1  NaN  NaN
    2  2.0    b
    3  3.0    b
    4  4.0    b
    5  5.0    b
    6  NaN  NaN
    7  NaN  NaN
    
  • Series和DataFrame hist方法现在接受 figsize 论据 (GH3834 )

  • 在连接操作期间,DatetimeIndex不再尝试转换混合整数索引 (GH3877 )

  • 感谢@SleepingPills,Timestamp.min和Timestamp.max现在分别代表有效的Timestamp实例,而不是默认的DateTim.min和Datetime.max

  • read_html 现在在找不到表并检测到BeautifulSoup==4.2.0时引发 (GH4214 )

实验特征#

  • 增加了实验 CustomBusinessDay 要支持的类 DateOffsets 带有定制的假日日历和定制的周面具。 (GH2301 )

    备注

    这使用了 numpy.busdaycalendar API是在Numpy 1.7中引入的,因此需要Numpy 1.7.0或更高版本。

    In [29]: from pandas.tseries.offsets import CustomBusinessDay
    
    In [30]: from datetime import datetime
    
    # As an interesting example, let's look at Egypt where
    # a Friday-Saturday weekend is observed.
    In [31]: weekmask_egypt = "Sun Mon Tue Wed Thu"
    
    # They also observe International Workers' Day so let's
    # add that for a couple of years
    In [32]: holidays = ["2012-05-01", datetime(2013, 5, 1), np.datetime64("2014-05-01")]
    
    In [33]: bday_egypt = CustomBusinessDay(holidays=holidays, weekmask=weekmask_egypt)
    
    In [34]: dt = datetime(2013, 4, 30)
    
    In [35]: print(dt + 2 * bday_egypt)
    2013-05-05 00:00:00
    
    In [36]: dts = pd.date_range(dt, periods=5, freq=bday_egypt)
    
    In [37]: print(pd.Series(dts.weekday, dts).map(pd.Series("Mon Tue Wed Thu Fri Sat Sun".split())))
    2013-04-30    Tue
    2013-05-02    Thu
    2013-05-05    Sun
    2013-05-06    Mon
    2013-05-07    Tue
    Freq: C, dtype: object
    

错误修复#

  • Plotting functions now raise a TypeError before trying to plot anything if the associated objects have a dtype of object (GH1818, GH3572, GH3911, GH3912), but they will try to convert object arrays to numeric arrays if possible so that you can still plot, for example, an object array with floats. This happens before any drawing takes place which eliminates any spurious plots from showing up.

  • fillna 方法现在引发 TypeError 如果 value 参数是列表或元组。

  • Series.str 现在支持迭代 (GH3638 )。中的每个字符串的各个元素进行迭代 Series 。每次迭代都会产生一个 Series 在原始文件的每个索引处使用单个字符 SeriesNaN 。例如,

    In [38]: strs = "go", "bow", "joe", "slow"
    
    In [39]: ds = pd.Series(strs)
    
    In [40]: for s in ds.str:
       ....:     print(s)
       ....: 
    0    g
    1    b
    2    j
    3    s
    dtype: object
    0    o
    1    o
    2    o
    3    l
    dtype: object
    0    NaN
    1      w
    2      e
    3      o
    dtype: object
    0    NaN
    1    NaN
    2    NaN
    3      w
    dtype: object
    
    In [41]: s
    Out[41]: 
    0    NaN
    1    NaN
    2    NaN
    3      w
    dtype: object
    
    In [42]: s.dropna().values.item() == "w"
    Out[42]: True
    

    迭代器产生的最后一个元素将是 Series 中最长字符串的最后一个元素。 Series 所有其他元素都是 NaN 。在这里,因为 'slow' 是最长的字符串,并且没有其他长度相同的字符串 'w' 中的唯一非空字符串。 Series

  • HDFStore

    • 将保留有关娱乐的索引属性(频率、频率、名称 (GH3499 )

    • 将使用 AttributeConflictWarning 如果您尝试以不同于现有频率的频率追加索引,或试图以不同于现有名称的名称追加索引

    • 支持使用时区作为DATA_COLUMNS的类日期列 (GH2852 )

  • 澄清非唯一索引支持 (GH3468 )。

    • 修复将新索引分配给DataFrame中的重复索引将失败 (GH3468 )

    • 修复具有重复索引的DataFrame的构造

    • Ref_locs支持允许跨dtype复制索引,允许IGET支持始终查找索引(即使跨dtype) (GH2194 )

    • 具有非唯一索引的DataFrame上的应用程序映射现在起作用(已删除警告) (GH2786 ),并修复 (GH3230 )

    • 修复为_CSV以处理非唯一列 (GH3495 )

    • 带有getitem的重复索引将以正确的顺序返回项 (GH3455GH3457 )并处理缺少的元素,如唯一索引 (GH3561 )

    • 具有和空DataFrame.from_Records的重复索引将返回正确的帧 (GH3562 )

    • 固定了在数据类型之间存在重复项时生成非唯一列的合并 (GH3602 )

    • 允许插入/删除非唯一列 (GH3679 )

    • 使用切片通过的非唯一索引 loc 和固定的朋友 (GH3659 )

    • 允许插入/删除非唯一列 (GH3679 )

    • 延展 reindex 正确处理非唯一索引 (GH3679 )

    • DataFrame.itertuples() 现在可以使用具有重复列名的框架 (GH3873 )

    • Bug in non-unique indexing via iloc (GH4017); added takeable argument to reindex for location-based taking

    • Allow non-unique indexing in series via .ix/.loc and __getitem__ (GH4246)

    • Fixed non-unique indexing memory allocation issue with .ix/.loc (GH4280)

  • DataFrame.from_records 不接受空的重新数组 (GH3682 )

  • read_html 现在可以正确地跳过测试 (GH3741 )

  • 修复了以下位置的错误 DataFrame.replace 方法中使用已编译的正则表达式 to_replace 论据不起作用 (GH3907 )

  • 改进 network 测试要捕获的装饰符 IOError (因此 URLError 也是)。增列 with_connectivity_check 修饰器允许显式检查网站作为代理,以查看是否有网络连接。另外,新的 optional_args 装饰师的装饰工厂。 (GH3910GH3914 )

  • 修复了打开太多套接字从而导致连接重置问题的测试问题 (GH3982GH3985GH4028GH4054 )

  • 修复了TEST_YAHOO、TEST_GOOGLE中未检索但正在访问符号的失败测试 (GH3982GH3985GH4028GH4054 )

  • Series.hist 如果没有传递,现在将从当前环境中获取该数字

  • 修复了1xN DataFrame在1xN掩码上呕吐的错误 (GH4071 )

  • 固定运行 tox 在python3下,正在以一种不兼容的方式重写Pickle导入 (GH4062GH4063 )

  • 修正了未将共享和共享传递给GROUPPED_HIST的错误 (GH4089 )

  • 修复了中的错误 DataFrame.replace 当regex=FALSE时,不会迭代嵌套的字典 (GH4115 )

  • Fixed bug in the parsing of microseconds when using the format argument in to_datetime (GH4152)

  • Fixed bug in PandasAutoDateLocator where invert_xaxis triggered incorrectly MilliSecondLocator (GH3990)

  • 修复了在matplotlib 1.1.1的无效色彩映射表上未引发的打印错误 (GH4215 )

  • Fixed the legend displaying in DataFrame.plot(kind='kde') (GH4216)

  • 修复了索引片不带有名称属性的错误 (GH4226 )

  • 修复了初始化过程中的错误 DatetimeIndex 具有位于特定时区的字符串数组 (GH4229 )

  • 修复了未正确跳过html5lib的错误 (GH4265 )

  • 修复了GET_DATA_FAMAFRATCH没有使用正确的文件边缘的错误 (GH4281 )

请参阅 full release notes 或在GitHub上的问题跟踪器上查看完整的列表。

贡献者#

共有50人为此次发布贡献了补丁。名字中带有“+”的人第一次贡献了一个补丁。

  • Andy Hayden

  • Chang She

  • Christopher Whelan

  • Damien Garaud

  • Dan Allan

  • Dan Birken

  • Dieter Vandenbussche

  • Dražen Lučanin

  • Gábor Lipták +

  • Jeff Mellen +

  • Jeff Tratner +

  • Jeffrey Tratner +

  • Jonathan deWerd +

  • Joris Van den Bossche +

  • Juraj Niznan +

  • Karmel Allison

  • Kelsey Jordahl

  • Kevin Stone +

  • Kieran O'Mahony

  • Kyle Meyer +

  • Mike Kelly +

  • PKEuS +

  • Patrick O'Brien +

  • Phillip Cloud

  • Richard Höchenberger +

  • Skipper Seabold

  • SleepingPills +

  • Tobias Brandt

  • Tom Farnbauer +

  • TomAugspurger +

  • Trent Hauck +

  • Wes McKinney

  • Wouter Overmeire

  • Yaroslav Halchenko

  • conmai +

  • danielballan +

  • davidshinn +

  • dieterv77

  • duozhang +

  • ejnens +

  • gliptak +

  • jniznan +

  • jreback

  • lexual

  • nipunreddevil +

  • ogiaquino +

  • stonebig +

  • tim smith +

  • timmie

  • y-p