版本0.11.0(2013年4月22日)#

这是从0.10.1开始的一个主要版本,包括许多新功能和增强功能,以及大量的错误修复。选择数据的方法增加了相当多的内容,Dtype支持现在已经完全成熟。还有一些重要的API变化,长期使用大Pandas的人应该密切关注。

文档中有一个新的部分, 10 Minutes to Pandas ,主要面向新用户。

文档中有一个新的部分, Cookbook ,收集了Pandas的有用食谱(我们想要贡献!)

现在有几个库 Recommended Dependencies

选择选项#

从0.11.0开始,对象选择增加了许多用户请求的功能,以支持更明确的基于位置的索引。Pandas现在支持三种类型的多轴分度。

  • .loc 是严格基于标签的,将提高 KeyError 当未找到项目时,允许的输入为:

    • 单个标签,例如 5'a' ,(请注意 5 被解释为 标签 在索引中。此用法是 not 沿索引的整数位置)

    • 标签列表或标签数组 ['a', 'b', 'c']

    • 带标签的切片对象 'a':'f' ,(请注意,与通常的 Python 切片相反, both 包括开始和停止!)

    • 布尔数组

    见更多 Selection by Label

  • .iloc 严格基于整数位置(从 0length-1 轴),将引发 IndexError 当请求的索引超出界限时。允许的输入包括:

    • 一个整数,例如 5

    • 整数列表或整数数组 [4, 3, 0]

    • 带有整型的切片对象 1:7

    • 布尔数组

    见更多 Selection by Position

  • .ix 支持混合整数和基于标签的访问。它主要是基于标签的,但将回退到整数位置访问。 .ix 是最通用的,并且将支持以下任何输入 .loc.iloc 以及对浮点标签方案的支持。 .ix 在处理混合位置索引和基于标签的分层索引时特别有用。

    与使用整数切片时一样 .ix 根据切片是被解释为基于位置的还是基于标签的,具有不同的行为,通常最好是显式并使用 .iloc.loc

    见更多 Advanced IndexingAdvanced Hierarchical

所选内容不推荐使用#

从0.11.0版开始,这些方法 may 在未来的版本中将被弃用。

  • irow

  • icol

  • iget_value

请参阅部分 Selection by Position 作为替代品。

数据类型#

数值数据类型将传播并可以在DataFrame中共存。如果传递数据类型(直接通过 dtype 关键字,传递的 ndarray ,或及格 Series ,则它将在DataFrame操作中保留。此外,不同的数字数据类型将 NOT 结合在一起。下面的例子会让你尝一尝。

In [1]: df1 = pd.DataFrame(np.random.randn(8, 1), columns=['A'], dtype='float32')

In [2]: df1
Out[2]: 
          A
0  0.469112
1 -0.282863
2 -1.509058
3 -1.135632
4  1.212112
5 -0.173215
6  0.119209
7 -1.044236

In [3]: df1.dtypes
Out[3]: 
A    float32
dtype: object

In [4]: df2 = pd.DataFrame({'A': pd.Series(np.random.randn(8), dtype='float16'),
   ...:                     'B': pd.Series(np.random.randn(8)),
   ...:                     'C': pd.Series(range(8), dtype='uint8')})
   ...: 

In [5]: df2
Out[5]: 
          A         B  C
0 -0.861816 -0.424972  0
1 -2.105469  0.567020  1
2 -0.494873  0.276232  2
3  1.072266 -1.087401  3
4  0.721680 -0.673690  4
5 -0.706543  0.113648  5
6 -1.040039 -1.478427  6
7  0.271973  0.524988  7

In [6]: df2.dtypes
Out[6]: 
A    float16
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.392704 -0.424972  0.0
1 -2.388332  0.567020  1.0
2 -2.003932  0.276232  2.0
3 -0.063367 -1.087401  3.0
4  1.933792 -0.673690  4.0
5 -0.879758  0.113648  5.0
6 -0.920830 -1.478427  6.0
7 -0.772263  0.524988  7.0

In [9]: df3.dtypes
Out[9]: 
A    float32
B    float64
C    float64
dtype: object

数据类型转换#

这是较低公分母的向上转换,这意味着您获得的数据类型可以容纳所有类型

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的构造将使用默认数据类型 int64float64不考虑平台 。这与早先的Pandas版本相比并没有明显的变化。如果指定dtype,则它们 WILL 然而,要受到尊重 (GH2837 )

以下所有结果都将导致 int64 数据类型

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

Keep in mind that DataFrame(np.array([1,2])) WILL result in int32 on 32-bit platforms!

向上转换陷阱

对整型数据执行索引操作可以很容易地向上转换数据。在以下情况下,将保留输入数据的数据类型 nans 都没有被介绍。

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

而浮点数据类型保持不变。

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

日期时间转换#

日期时间64 [ns] DataFrame(或系列)中的列允许使用 np.nan 来指示NaN值,除了传统的 NaT ,或者不是一次。这允许以通用方式进行方便的NaN设置。更有甚者 datetime64[ns] 默认情况下,在传递类似日期时间的对象( 此更改是在0.10.1中引入的 ) (GH2809GH2810 )

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[ns]    1
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 ,隐式转换为 NaTnp.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[ns]')

In [21]: s[1] = np.nan

In [22]: s
Out[22]: 
0   2001-01-02
1          NaT
2   2001-01-02
dtype: datetime64[ns]

In [23]: s.dtype
Out[23]: dtype('<M8[ns]')

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()方法添加到索引中,以便于创建索引器 (GH3275 )

  • HDFStore

    • 添加了方法 select_column 若要从表中选择单个列作为系列,请执行以下操作。

    • 不推荐使用 unique 方法,可以通过以下方式复制 select_column(key,column).unique()

    • min_itemsize 参数设置为 append 现在将自动为传递的键创建data_Columns

增强#

  • 在某些情况下,df.to_csv()的性能提高了10倍。 (GH3059 )

  • Numexpr现在是一家 Recommended Dependencies ,以加速某些类型的数值和布尔运算

  • 瓶颈现在是 Recommended Dependencies ,以加速某些类型的 nan 运营

  • HDFStore

    • 支持 read_hdf/to_hdf API类似于 read_csv/to_csv

      In [27]: df = pd.DataFrame({'A': range(5), 'B': range(5)})
      
      In [28]: df.to_hdf('store.h5', 'table', append=True)
      ---------------------------------------------------------------------------
      ModuleNotFoundError                       Traceback (most recent call last)
      File /usr/local/lib/python3.10/dist-packages/pandas-1.5.0.dev0+697.gf9762d8f52-py3.10-linux-x86_64.egg/pandas/compat/_optional.py:139, in import_optional_dependency(name, extra, errors, min_version)
          138 try:
      --> 139     module = importlib.import_module(name)
          140 except ImportError:
      
      File /usr/lib/python3.10/importlib/__init__.py:126, in import_module(name, package)
          125         level += 1
      --> 126 return _bootstrap._gcd_import(name[level:], package, level)
      
      File <frozen importlib._bootstrap>:1050, in _gcd_import(name, package, level)
      
      File <frozen importlib._bootstrap>:1027, in _find_and_load(name, import_)
      
      File <frozen importlib._bootstrap>:1004, in _find_and_load_unlocked(name, import_)
      
      ModuleNotFoundError: No module named 'tables'
      
      During handling of the above exception, another exception occurred:
      
      ImportError                               Traceback (most recent call last)
      Input In [28], in <cell line: 1>()
      ----> 1 df.to_hdf('store.h5', 'table', append=True)
      
      File /usr/local/lib/python3.10/dist-packages/pandas-1.5.0.dev0+697.gf9762d8f52-py3.10-linux-x86_64.egg/pandas/core/generic.py:2655, in NDFrame.to_hdf(self, path_or_buf, key, mode, complevel, complib, append, format, index, min_itemsize, nan_rep, dropna, data_columns, errors, encoding)
         2651 from pandas.io import pytables
         2653 # Argument 3 to "to_hdf" has incompatible type "NDFrame"; expected
         2654 # "Union[DataFrame, Series]" [arg-type]
      -> 2655 pytables.to_hdf(
         2656     path_or_buf,
         2657     key,
         2658     self,  # type: ignore[arg-type]
         2659     mode=mode,
         2660     complevel=complevel,
         2661     complib=complib,
         2662     append=append,
         2663     format=format,
         2664     index=index,
         2665     min_itemsize=min_itemsize,
         2666     nan_rep=nan_rep,
         2667     dropna=dropna,
         2668     data_columns=data_columns,
         2669     errors=errors,
         2670     encoding=encoding,
         2671 )
      
      File /usr/local/lib/python3.10/dist-packages/pandas-1.5.0.dev0+697.gf9762d8f52-py3.10-linux-x86_64.egg/pandas/io/pytables.py:312, in to_hdf(path_or_buf, key, value, mode, complevel, complib, append, format, index, min_itemsize, nan_rep, dropna, data_columns, errors, encoding)
          310 path_or_buf = stringify_path(path_or_buf)
          311 if isinstance(path_or_buf, str):
      --> 312     with HDFStore(
          313         path_or_buf, mode=mode, complevel=complevel, complib=complib
          314     ) as store:
          315         f(store)
          316 else:
      
      File /usr/local/lib/python3.10/dist-packages/pandas-1.5.0.dev0+697.gf9762d8f52-py3.10-linux-x86_64.egg/pandas/io/pytables.py:573, in HDFStore.__init__(self, path, mode, complevel, complib, fletcher32, **kwargs)
          570 if "format" in kwargs:
          571     raise ValueError("format is not a defined argument for HDFStore")
      --> 573 tables = import_optional_dependency("tables")
          575 if complib is not None and complib not in tables.filters.all_complibs:
          576     raise ValueError(
          577         f"complib only supports {tables.filters.all_complibs} compression."
          578     )
      
      File /usr/local/lib/python3.10/dist-packages/pandas-1.5.0.dev0+697.gf9762d8f52-py3.10-linux-x86_64.egg/pandas/compat/_optional.py:142, in import_optional_dependency(name, extra, errors, min_version)
          140 except ImportError:
          141     if errors == "raise":
      --> 142         raise ImportError(msg)
          143     else:
          144         return None
      
      ImportError: Missing optional dependency 'pytables'.  Use pip or conda to install pytables.
      
      In [29]: pd.read_hdf('store.h5', 'table', where=['index > 2'])
      ---------------------------------------------------------------------------
      FileNotFoundError                         Traceback (most recent call last)
      Input In [29], in <cell line: 1>()
      ----> 1 pd.read_hdf('store.h5', 'table', where=['index > 2'])
      
      File /usr/local/lib/python3.10/dist-packages/pandas-1.5.0.dev0+697.gf9762d8f52-py3.10-linux-x86_64.egg/pandas/io/pytables.py:428, in read_hdf(path_or_buf, key, mode, errors, where, start, stop, columns, iterator, chunksize, **kwargs)
          425     exists = False
          427 if not exists:
      --> 428     raise FileNotFoundError(f"File {path_or_buf} does not exist")
          430 store = HDFStore(path_or_buf, mode=mode, errors=errors, **kwargs)
          431 # can't auto open/close if we are using an iterator
          432 # so delegate to the iterator
      
      FileNotFoundError: File store.h5 does not exist
      
    • 提供对虚线属性的访问 get 从商店,例如 store.df == store['df']

    • new keywords iterator=boolean, and chunksize=number_in_a_chunk are provided to support iteration on select and select_as_multiple (GH3076)

  • 现在,您可以从 无序 时间序列类似于 有条不紊 时装剧 (GH2437 )

  • 您现在可以使用字符串从具有类似日期的索引的DataFrame中进行选择,方法与Series类似 (GH3070 )

    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代替BeautifulSoup来抓取html(lxml更快)。

    • 调用创建它们的方法时,会自动创建用于调用和放置的新实例变量。这适用于当月,其中实例变量只是 callsputs 。也适用于未来的到期月份,并将实例变量另存为 callsMMYYputsMMYY ,在哪里 MMYY 分别是期权到期的月份和年份。

    • Options.get_near_stock_price 现在允许用户指定要获取相关选项数据的月份。

    • Options.get_forward_data 现在有可选的Kwarg nearabove_below 。这允许用户指定他们是否只想返回当前股价附近的期权的前瞻性数据。这只从Options.get_near_stock_Price而不是Options.get_xxx_data()获取数据 (GH2758 )。

  • 光标坐标信息现在显示在时间序列图中。

  • 添加了选项 display.max_seq_items 控制每个打印顺序打印的元素的数量。 (GH2979 )

  • 添加了选项 display.chop_threshold 控制小数值的显示。 (GH2739 )

  • 添加了选项 display.max_info_rows 以防止为超过1M行的帧计算VERBOSE_INFO(可配置)。 (GH2807GH2918 )

  • Value_Counts()现在接受归一化直方图的“Normize”参数。 (GH2710 )。

  • 现在,DataFrame.from_Records不仅接受dicts,还接受集合的任何实例。映射ABC。

  • 添加了选项 display.mpl_style 为情节提供了更时尚的视觉风格。基于https://gist.github.com/huyng/816622 (GH3075 )。

  • 对于数值运算,将布尔值视为整数(值1和0)。 (GH2641 )

  • To_html()现在接受一个可选的“ESCAPE”参数来控制保留的HTML字符转义(默认情况下启用)和转义 & ,此外, <> 。 (GH2919 )

请参阅 full release notes 或在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