Pandas-2-2-中文文档-六十-
Pandas 2.2 中文文档(六十)
版本 0.13.0(2014 年 1 月 3 日)
这是从 0.12.0 开始的一个重大版本发布,包括了许多 API 变更、几个新功能和增强以及大量的错误修复。
主要亮点包括:
-
对新索引类型
Float64Index
的支持,以及其他索引增强 -
HDFStore
对查询规范有了新的基于字符串的语法 -
对插值的新方法的支持
-
更新的
timedelta
操作 -
新的字符串操作方法
extract
-
对偏移量的纳秒支持
-
DataFrames 的
isin
添加了几个试验性功能,包括:
-
表达式评估的新的
eval/query
方法 -
对
msgpack
序列化的支持 -
Google 的
BigQuery
的 i/o 接口
有几个新的或更新的文档部分,包括:
-
与 SQL 的比较,对于熟悉 SQL 但仍在学习 pandas 的人来说应该很有用。
-
与 R 的比较,从 R 到 pandas 的成语翻译。
-
性能增强,使用
eval/query
提高 pandas 性能的方法。
警告
在 0.13.0 中,Series
在内部已经进行了重构,不再是子类 ndarray
,而是子类 NDFrame
,类似于其他 pandas 容器。这应该是一个透明的改变,只有非常有限的 API 影响。见 内部重构
API 变更
-
read_excel
现在支持在其sheetname
参数中使用整数来指定要读取的表的索引 (GH 4301)。 -
文本解析器现在将任何看起来像 inf 的内容(“inf”、“Inf”、“-Inf”、“iNf”等)视为无穷大。 (GH 4220, GH 4219),影响了
read_table
、read_csv
等。 -
pandas
现在与 Python 2/3 兼容,无需使用 2to3,这要归功于 @jtratner。因此,pandas 现在更广泛地使用迭代器。这也导致将 Benjamin Peterson 的six
库的实质性部分引入了 compat。 (GH 4384, GH 4375, GH 4372) -
pandas.util.compat
和pandas.util.py3compat
已合并为pandas.compat
。pandas.compat
现在包括许多函数,允许 2/3 兼容性。它包含 range、filter、map 和 zip 的列表和迭代器版本,以及其他必要的元素,用于 Python 3 兼容性。lmap
、lzip
、lrange
和lfilter
都生成列表而不是迭代器,以与numpy
、下标和pandas
构造函数兼容。(GH 4384, GH 4375, GH 4372) -
Series.get
使用负索引器现在返回与[]
相同的结果 (GH 4390) -
更改了
Index
和MultiIndex
处理元数据(levels
、labels
和names
)的方式 (GH 4039):# previously, you would have set levels or labels directly >>> pd.index.levels = [[1, 2, 3, 4], [1, 2, 4, 4]] # now, you use the set_levels or set_labels methods >>> index = pd.index.set_levels([[1, 2, 3, 4], [1, 2, 4, 4]]) # similarly, for names, you can rename the object # but setting names is not deprecated >>> index = pd.index.set_names(["bob", "cranberry"]) # and all methods take an inplace kwarg - but return None >>> pd.index.set_names(["bob", "cranberry"], inplace=True)
-
所有 与
NDFrame
对象的除法现在都是 truedivision,无论未来的导入如何。这意味着对 pandas 对象进行操作将默认使用 浮点 除法,并返回浮点 dtype。您可以使用//
和floordiv
进行整数除法。整数除法
In [3]: arr = np.array([1, 2, 3, 4]) In [4]: arr2 = np.array([5, 3, 2, 1]) In [5]: arr / arr2 Out[5]: array([0, 0, 1, 4]) In [6]: pd.Series(arr) // pd.Series(arr2) Out[6]: 0 0 1 0 2 1 3 4 dtype: int64
真除法
In [7]: pd.Series(arr) / pd.Series(arr2) # no future import required Out[7]: 0 0.200000 1 0.666667 2 1.500000 3 4.000000 dtype: float64
-
如果
downcast='infer'
被传递给fillna/ffill/bfill
,则推断并降级 dtype (GH 4604) -
__nonzero__
对于所有的 NDFrame 对象,现在会引发ValueError
,这恢复到了 (GH 1073, GH 4633) 的行为。查看 注意事项 以获取更详细的讨论。这样可以防止在 整个 pandas 对象上进行布尔比较,这在本质上是模棱两可的。这些都会引发
ValueError
。>>> df = pd.DataFrame({'A': np.random.randn(10), ... 'B': np.random.randn(10), ... 'C': pd.date_range('20130101', periods=10) ... }) ... >>> if df: ... pass ... Traceback (most recent call last): ... ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). >>> df1 = df >>> df2 = df >>> df1 and df2 Traceback (most recent call last): ... ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). >>> d = [1, 2, 3] >>> s1 = pd.Series(d) >>> s2 = pd.Series(d) >>> s1 and s2 Traceback (most recent call last): ... ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
向
NDFrame
对象添加了.bool()
方法,以便评估单元素布尔 Series:>>> pd.Series([True]).bool() True >>> pd.Series([False]).bool() False >>> pd.DataFrame([[True]]).bool() True >>> pd.DataFrame([[False]]).bool() False
-
所有非 Index NDFrames(
Series
、DataFrame
、Panel
、Panel4D
、SparsePanel
等),现在支持整套算术运算符和算术灵活方法(add、sub、mul 等)。SparsePanel
不支持与非标量的pow
或mod
。(GH 3765) -
Series
和DataFrame
现在有一个mode()
方法来计算按轴/Series 计算统计模式。(GH 5367) -
现在默认情况下,链式赋值将会在用户对副本进行赋值时发出警告。可以通过选项
mode.chained_assignment
进行更改,允许的选项为raise/warn/None
。查看 文档。In [1]: dfc = pd.DataFrame({'A': ['aaa', 'bbb', 'ccc'], 'B': [1, 2, 3]}) In [2]: pd.set_option('chained_assignment', 'warn')
如果尝试这样做,将显示以下警告/异常。
In [3]: dfc.loc[0]['A'] = 1111
Traceback (most recent call last) ... SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_index,col_indexer] = value instead
这是正确的赋值方法。
In [4]: dfc.loc[0, 'A'] = 11 In [5]: dfc Out[5]: A B 0 11 1 1 bbb 2 2 ccc 3
-
Panel.reindex
具有以下调用签名Panel.reindex(items=None, major_axis=None, minor_axis=None, **kwargs)
以符合其他
NDFrame
对象。查看 内部重构 获取更多信息。 -
Series.argmin
和Series.argmax
现在别名为Series.idxmin
和Series.idxmax
。这些返回索引在 0.13.0 之前,
min
或max
元素分别返回最小/最大元素的位置。(GH 6214)
之前版本的废弃/更改
这些是在 0.12 或之前宣布的更改,将在 0.13.0 中生效
-
移除废弃的
Factor
(GH 3650) -
移除废弃的
set_printoptions/reset_printoptions
(GH 3046) -
移除废弃的
_verbose_info
(GH 3215) -
从
pandas.io.parsers
中移除废弃的read_clipboard/to_clipboard/ExcelFile/ExcelWriter
(GH 3717) 这些作为主 pandas 命名空间中的函数可用(例如pd.read_clipboard
) -
tupleize_cols
的默认值现在对于to_csv
和read_csv
都是False
。在 0.12 中有明确警告 (GH 3604) -
display.max_seq_len
的默认值现在是 100 而不是None
。这会在各个地方激活长序列的截断显示("...")。(GH 3391)
废弃
在 0.13.0 中废弃
-
废弃了
iterkv
,将在将来的版本中移除(这是绕过2to3
更改的iteritems
的别名)。(GH 4384, GH 4375, GH 4372) -
废弃了字符串方法
match
,其作用现在更符合习惯的是extract
。在将来的版本中,match
的默认行为将变为类似于contains
,返回一个布尔索引器。(它们的区别在于严格性:match
依赖于re.match
,而contains
依赖于re.search
。)在此版本中,废弃的行为是默认的,但新行为可以通过关键字参数as_indexer=True
获得。
索引 API 更改
在 0.13 之前,不可能使用标签索引器(.loc/.ix
)设置特定轴索引中不包含的值。(GH 2578)。参见文档
在 Series
情���下,这实际上是一个追加操作
In [6]: s = pd.Series([1, 2, 3])
In [7]: s
Out[7]:
0 1
1 2
2 3
dtype: int64
In [8]: s[5] = 5.
In [9]: s
Out[9]:
0 1.0
1 2.0
2 3.0
5 5.0
dtype: float64
In [10]: dfi = pd.DataFrame(np.arange(6).reshape(3, 2),
....: columns=['A', 'B'])
....:
In [11]: dfi
Out[11]:
A B
0 0 1
1 2 3
2 4 5
这以前会引发 KeyError
In [12]: dfi.loc[:, 'C'] = dfi.loc[:, 'A']
In [13]: dfi
Out[13]:
A B C
0 0 1 0
1 2 3 2
2 4 5 4
这就像一个 append
操作。
In [14]: dfi.loc[3] = 5
In [15]: dfi
Out[15]:
A B C
0 0 1 0
1 2 3 2
2 4 5 4
3 5 5 5
对 Panel 的任意轴进行设置操作会将输入对齐到 Panel
In [20]: p = pd.Panel(np.arange(16).reshape(2, 4, 2),
....: items=['Item1', 'Item2'],
....: major_axis=pd.date_range('2001/1/12', periods=4),
....: minor_axis=['A', 'B'], dtype='float64')
....:
In [21]: p
Out[21]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 4 (major_axis) x 2 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis: 2001-01-12 00:00:00 to 2001-01-15 00:00:00
Minor_axis axis: A to B
In [22]: p.loc[:, :, 'C'] = pd.Series([30, 32], index=p.items)
In [23]: p
Out[23]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 4 (major_axis) x 3 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis: 2001-01-12 00:00:00 to 2001-01-15 00:00:00
Minor_axis axis: A to C
In [24]: p.loc[:, :, 'C']
Out[24]:
Item1 Item2
2001-01-12 30.0 32.0
2001-01-13 30.0 32.0
2001-01-14 30.0 32.0
2001-01-15 30.0 32.0
Float64Index API 更改
-
添加了新的索引类型
Float64Index
。当在索引创建中传递浮点值时,将自动创建此索引。这使得基于纯标签的切片范式可以使[],ix,loc
用于标量索引和切片的工作完全相同。(GH 263)默认情况下构造是针对浮点类型值的。
In [16]: index = pd.Index([1.5, 2, 3, 4.5, 5]) In [17]: index Out[17]: Index([1.5, 2.0, 3.0, 4.5, 5.0], dtype='float64') In [18]: s = pd.Series(range(5), index=index) In [19]: s Out[19]: 1.5 0 2.0 1 3.0 2 4.5 3 5.0 4 dtype: int64
对于
[],.ix,.loc
的标量选择始终基于标签。整数将匹配相等的浮点索引(例如,3
等同于3.0
)In [20]: s[3] Out[20]: 2 In [21]: s.loc[3] Out[21]: 2
唯一的位置索引是通过
iloc
进行的In [22]: s.iloc[3] Out[22]: 3
未找到的标量索引将引发
KeyError
切片始终是在索引的值上进行的,对于
[],ix,loc
始终是位置性的,对于iloc
始终是位置性的In [23]: s[2:4] Out[23]: 2.0 1 3.0 2 dtype: int64 In [24]: s.loc[2:4] Out[24]: 2.0 1 3.0 2 dtype: int64 In [25]: s.iloc[2:4] Out[25]: 3.0 2 4.5 3 dtype: int64
在浮点索引中,允许使用浮点数进行切片
In [26]: s[2.1:4.6] Out[26]: 3.0 2 4.5 3 dtype: int64 In [27]: s.loc[2.1:4.6] Out[27]: 3.0 2 4.5 3 dtype: int64
-
其他索引类型上的索引被保留(并且对于
[],ix
是位置性的后备),唯一的例外是,在非Float64Index
上进行浮点切片现在将引发TypeError
。In [1]: pd.Series(range(5))[3.5] TypeError: the label [3.5] is not a proper indexer for this index type (Int64Index) In [1]: pd.Series(range(5))[3.5:4.5] TypeError: the slice start [3.5] is not a proper indexer for this index type (Int64Index)
在将来的版本中将弃用使用标量浮点索引器,但目前允许使用。
In [3]: pd.Series(range(5))[3.0] Out[3]: 3
HDFStore API 更改
-
查询格式更改。现在支持更类似字符串的查询格式。请参阅文档。
In [28]: path = 'test.h5' In [29]: dfq = pd.DataFrame(np.random.randn(10, 4), ....: columns=list('ABCD'), ....: index=pd.date_range('20130101', periods=10)) ....: In [30]: dfq.to_hdf(path, key='dfq', format='table', data_columns=True)
使用布尔表达式,进行内联函数评估。
In [31]: pd.read_hdf(path, 'dfq', ....: where="index>Timestamp('20130104') & columns=['A', 'B']") ....: Out[31]: A B 2013-01-05 -0.424972 0.567020 2013-01-06 -0.673690 0.113648 2013-01-07 0.404705 0.577046 2013-01-08 -0.370647 -1.157892 2013-01-09 1.075770 -0.109050 2013-01-10 0.357021 -0.674600
使用内联列引用
In [32]: pd.read_hdf(path, 'dfq', ....: where="A>0 or C>0") ....: Out[32]: A B C D 2013-01-01 0.469112 -0.282863 -1.509059 -1.135632 2013-01-02 1.212112 -0.173215 0.119209 -1.044236 2013-01-04 0.721555 -0.706771 -1.039575 0.271860 2013-01-05 -0.424972 0.567020 0.276232 -1.087401 2013-01-07 0.404705 0.577046 -1.715002 -1.039268 2013-01-09 1.075770 -0.109050 1.643563 -1.469388 2013-01-10 0.357021 -0.674600 -1.776904 -0.968914
-
format
关键字现在替换了table
关键字;允许的值为fixed(f)
或table(t)
,与之前<0.13.0 相同的默认值保留,例如put
意味着fixed
格式,append
意味着table
格式。可以通过设置io.hdf.default_format
选项将此默认格式设置为选项。In [33]: path = 'test.h5' In [34]: df = pd.DataFrame(np.random.randn(10, 2)) In [35]: df.to_hdf(path, key='df_table', format='table') In [36]: df.to_hdf(path, key='df_table2', append=True) In [37]: df.to_hdf(path, key='df_fixed') In [38]: with pd.HDFStore(path) as store: ....: print(store) ....: <class 'pandas.io.pytables.HDFStore'> File path: test.h5
-
显著的表写入性能改进
-
处理以表格格式传递的
Series
(GH 4330) -
现在可以在表中序列化
timedelta64[ns]
dtype(GH 3577),请参阅文档。 -
添加了一个
is_open
属性,指示底层文件句柄是否打开;关闭的存储现在在查看存储时将报告“CLOSED”(而不是引发错误)(GH 4409) -
关闭
HDFStore
现在将关闭HDFStore
的实例,但仅在所有打开句柄的引用计数(由PyTables
)为 0 时才会关闭实际文件。基本上,您有一个由变量引用的本地HDFStore
实例。一旦关闭,它将报告已关闭。其他引用(指向同一文件)将继续操作,直到它们自己关闭。对已关闭文件执行操作将引发ClosedFileError
In [39]: path = 'test.h5' In [40]: df = pd.DataFrame(np.random.randn(10, 2)) In [41]: store1 = pd.HDFStore(path) In [42]: store2 = pd.HDFStore(path) In [43]: store1.append('df', df) In [44]: store2.append('df2', df) In [45]: store1 Out[45]: <class 'pandas.io.pytables.HDFStore'> File path: test.h5 In [46]: store2 Out[46]: <class 'pandas.io.pytables.HDFStore'> File path: test.h5 In [47]: store1.close() In [48]: store2 Out[48]: <class 'pandas.io.pytables.HDFStore'> File path: test.h5 In [49]: store2.close() In [50]: store2 Out[50]: <class 'pandas.io.pytables.HDFStore'> File path: test.h5
-
删除了
_quiet
属性,如果从表中检索重复行,则替换为DuplicateWarning
(GH 4367) -
从
open
中删除了warn
参数。如果尝试使用mode='w'
打开文件句柄,则将引发PossibleDataLossError
异常(GH 4367) -
允许作为
where
条件传递位置数组或掩码(GH 4467)。请参阅文档以获取示例。 -
在
append
中添加关键字dropna=True
,以更改是否将所有 NaN 行写入存储(默认为True
,所有 NaN 行都不写入),也可以通过选项io.hdf.dropna_table
进行设置 (GH 4625) -
通过传递存储创建参数;可用于支持内存存储
DataFrame repr 变更
现在的 HTML 和纯文本表示 DataFrame
在超过一定大小后将显示表格的截断视图,而不是切换到简短的信息视图 (GH 4886,GH 5550)。这使得表示更加一致,因为小的 DataFrame 会变得更大。
要获取信息视图,请调用 DataFrame.info()
。如果你更喜欢大型 DataFrame 的信息视图作为 repr,则可以通过运行 set_option('display.large_repr', 'info')
来设置。
增强功能
-
df.to_clipboard()
学会了一个新的excel
关键字,可以让你直接将 df 数据粘贴到 excel 中(默认情况下启用)。(GH 5070). -
read_html
现在会引发URLError
,而不是捕获并引发ValueError
(GH 4303,GH 4305) -
添加了对
read_clipboard()
和to_clipboard()
的测试 (GH 4282) -
剪贴板功能现在可以与 PySide 一起使用 (GH 4282)
-
当绘图参数包含重叠的颜色和样式参数时,添加了更具信息性的错误消息 (GH 4402)
-
to_dict
现在接受records
作为可能的输出类型。返回一个以列为键的字典数组。(GH 4936) -
get_dummies
中的NaN
处理(GH 4446)与dummy_na
# previously, nan was erroneously counted as 2 here # now it is not counted at all In [51]: pd.get_dummies([1, 2, np.nan]) Out[51]: 1.0 2.0 0 True False 1 False True 2 False False # unless requested In [52]: pd.get_dummies([1, 2, np.nan], dummy_na=True) Out[52]: 1.0 2.0 NaN 0 True False False 1 False True False 2 False False True
-
timedelta64[ns]
操作。参见文档。警告
大多数这些操作需要
numpy >= 1.7
使用新的顶级
to_timedelta
,你可以将标准 timedelta 格式(由to_csv
生成)的标量或数组转换为 timedelta 类型(nanoseconds
中的np.timedelta64
)。In [53]: pd.to_timedelta('1 days 06:05:01.00003') Out[53]: Timedelta('1 days 06:05:01.000030') In [54]: pd.to_timedelta('15.5us') Out[54]: Timedelta('0 days 00:00:00.000015500') In [55]: pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan']) Out[55]: TimedeltaIndex(['1 days 06:05:01.000030', '0 days 00:00:00.000015500', NaT], dtype='timedelta64[ns]', freq=None) In [56]: pd.to_timedelta(np.arange(5), unit='s') Out[56]: TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:01', '0 days 00:00:02', '0 days 00:00:03', '0 days 00:00:04'], dtype='timedelta64[ns]', freq=None) In [57]: pd.to_timedelta(np.arange(5), unit='d') Out[57]: TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'], dtype='timedelta64[ns]', freq=None)
timedelta64[ns]
类型的 Series 现在可以除以另一个timedelta64[ns]
对象,或者转换为float64
类型的 Series。这是频率转换。参见文档。In [58]: import datetime In [59]: td = pd.Series(pd.date_range('20130101', periods=4)) - pd.Series( ....: pd.date_range('20121201', periods=4)) ....: In [60]: td[2] += np.timedelta64(datetime.timedelta(minutes=5, seconds=3)) In [61]: td[3] = np.nan In [62]: td Out[62]: 0 31 days 00:00:00 1 31 days 00:00:00 2 31 days 00:05:03 3 NaT dtype: timedelta64[ns]
# to days In [63]: td / np.timedelta64(1, 'D') Out[63]: 0 31.000000 1 31.000000 2 31.003507 3 NaN dtype: float64 In [64]: td.astype('timedelta64[D]') Out[64]: 0 31.0 1 31.0 2 31.0 3 NaN dtype: float64 # to seconds In [65]: td / np.timedelta64(1, 's') Out[65]: 0 2678400.0 1 2678400.0 2 2678703.0 3 NaN dtype: float64 In [66]: td.astype('timedelta64[s]') Out[66]: 0 2678400.0 1 2678400.0 2 2678703.0 3 NaN dtype: float64
将
timedelta64[ns]
Series 除以整数或整数 SeriesIn [63]: td * -1 Out[63]: 0 -31 days +00:00:00 1 -31 days +00:00:00 2 -32 days +23:54:57 3 NaT dtype: timedelta64[ns] In [64]: td * pd.Series([1, 2, 3, 4]) Out[64]: 0 31 days 00:00:00 1 62 days 00:00:00 2 93 days 00:15:09 3 NaT dtype: timedelta64[ns]
绝对的
DateOffset
对象可以等效地作为timedeltas
In [65]: from pandas import offsets In [66]: td + offsets.Minute(5) + offsets.Milli(5) Out[66]: 0 31 days 00:05:00.005000 1 31 days 00:05:00.005000 2 31 days 00:10:03.005000 3 NaT dtype: timedelta64[ns]
现在支持对时间增量的 Fillna
In [67]: td.fillna(pd.Timedelta(0)) Out[67]: 0 31 days 00:00:00 1 31 days 00:00:00 2 31 days 00:05:03 3 0 days 00:00:00 dtype: timedelta64[ns] In [68]: td.fillna(datetime.timedelta(days=1, seconds=5)) Out[68]: 0 31 days 00:00:00 1 31 days 00:00:00 2 31 days 00:05:03 3 1 days 00:00:05 dtype: timedelta64[ns]
你可以对时间增量进行数值缩减操作。
In [69]: td.mean() Out[69]: Timedelta('31 days 00:01:41') In [70]: td.quantile(.1) Out[70]: Timedelta('31 days 00:00:00')
-
plot(kind='kde')
现在接受可选参数bw_method
和ind
,传递给 scipy.stats.gaussian_kde()(对于 scipy >= 0.11.0)以设置带宽,并分别传递给 gkde.evaluate() 以指定评估的索引。详见 scipy 文档。(GH 4298) -
DataFrame 构造函数现在接受一个 numpy 掩码记录数组 (GH 3478)
-
新的向量化字符串方法
extract
更方便地返回正则表达式匹配。In [71]: pd.Series(['a1', 'b2', 'c3']).str.extract('ab') Out[71]: 0 0 1 1 2 2 NaN
不匹配的元素返回
NaN
。提取具有多个组的正则表达式返回一个每组一列的 DataFrame。In [72]: pd.Series(['a1', 'b2', 'c3']).str.extract('([ab])(\\d)') Out[72]: 0 1 0 a 1 1 b 2 2 NaN NaN
不匹配的元素返回一行
NaN
。因此,一系列混乱的字符串可以转换为一个索引类似的清理或更有用的字符串的 Series 或 DataFrame,而不需要使用get()
来访问元组或re.match
对象。命名组如
In [73]: pd.Series(['a1', 'b2', 'c3']).str.extract( ....: '(?P<letter>[ab])(?P<digit>\\d)') ....: Out[73]: letter digit 0 a 1 1 b 2 2 NaN NaN
还可以使用可选的组。
In [74]: pd.Series(['a1', 'b2', '3']).str.extract( ....: '(?P<letter>[ab])?(?P<digit>\\d)') ....: Out[74]: letter digit 0 a 1 1 b 2 2 NaN 3
-
read_stata
现在接受 Stata 13 格式 (GH 4291) -
如果数据正确分隔且列对齐,
read_fwf
现在可以从文件的前 100 行中推断列规格,使用提供给函数的分隔符 (GH 4488). -
支持纳秒时间作为偏移量
警告
这些操作需要
numpy >= 1.7
秒及以下范围内的期间转换已经重新设计并扩展到纳秒。现在支持纳秒级别的期间。
In [79]: pd.date_range('2013-01-01', periods=5, freq='5N') Out[79]: DatetimeIndex([ '2013-01-01 00:00:00', '2013-01-01 00:00:00.000000005', '2013-01-01 00:00:00.000000010', '2013-01-01 00:00:00.000000015', '2013-01-01 00:00:00.000000020'], dtype='datetime64[ns]', freq='5N')
或者使用频率作为偏移量
In [75]: pd.date_range('2013-01-01', periods=5, freq=pd.offsets.Nano(5)) Out[75]: DatetimeIndex([ '2013-01-01 00:00:00', '2013-01-01 00:00:00.000000005', '2013-01-01 00:00:00.000000010', '2013-01-01 00:00:00.000000015', '2013-01-01 00:00:00.000000020'], dtype='datetime64[ns]', freq='5ns')
时间戳可以在纳秒范围内修改
In [76]: t = pd.Timestamp('20130101 09:01:02') In [77]: t + pd.tseries.offsets.Nano(123) Out[77]: Timestamp('2013-01-01 09:01:02.000000123')
-
DataFrames 新增了一个名为
isin
的方法,与布尔索引非常兼容。isin
的参数,我们要将 DataFrame 与之比较的内容,可以是 DataFrame、Series、字典或值数组。详见文档。要获取满足任何条件的行:
In [78]: dfi = pd.DataFrame({'A': [1, 2, 3, 4], 'B': ['a', 'b', 'f', 'n']}) In [79]: dfi Out[79]: A B 0 1 a 1 2 b 2 3 f 3 4 n In [80]: other = pd.DataFrame({'A': [1, 3, 3, 7], 'B': ['e', 'f', 'f', 'e']}) In [81]: mask = dfi.isin(other) In [82]: mask Out[82]: A B 0 True False 1 False False 2 True True 3 False False In [83]: dfi[mask.any(axis=1)] Out[83]: A B 0 1 a 2 3 f
-
Series
现在支持一个to_frame
方法将其转换为单列 DataFrame (GH 5164) -
所有列在这里列出的 R 数据集
stat.ethz.ch/R-manual/R-devel/library/datasets/html/00Index.html
现在可以加载到 pandas 对象中# note that pandas.rpy was deprecated in v0.16.0 import pandas.rpy.common as com com.load_data('Titanic')
-
tz_localize
可以根据未定位数据的结构推断秋季日光节约转换 (GH 4230), 参见文档 -
DatetimeIndex
现在在 API 文档中,参见文档 -
json_normalize()
是一种从半结构化 JSON 数据创建平面表的新方法。参见文档(GH 1067) -
为 qtpandas 的 DataFrameModel 和 DataFrameWidget 添加了 PySide 支持。
-
Python csv 解析器现在支持 usecols(GH 4335)
-
频率增加了几个新的偏移量:
-
DataFrame 增加了一个新的
interpolate
方法,类似于 Series(GH 4434, GH 1892)In [84]: df = pd.DataFrame({'A': [1, 2.1, np.nan, 4.7, 5.6, 6.8], ....: 'B': [.25, np.nan, np.nan, 4, 12.2, 14.4]}) ....: In [85]: df.interpolate() Out[85]: A B 0 1.0 0.25 1 2.1 1.50 2 3.4 2.75 3 4.7 4.00 4 5.6 12.20 5 6.8 14.40
此外,
interpolate
的method
参数已扩展到包括'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'barycentric', 'krogh', 'piecewise_polynomial', 'pchip', 'polynomial', 'spline'
。这些新方法需要scipy。请参阅 Scipy 参考指南和文档,了解各种方法何时适用。参见文档。Interpolate 现在还接受一个
limit
关键字参数。这与fillna
的限制类似:In [86]: ser = pd.Series([1, 3, np.nan, np.nan, np.nan, 11]) In [87]: ser.interpolate(limit=2) Out[87]: 0 1.0 1 3.0 2 5.0 3 7.0 4 NaN 5 11.0 dtype: float64
-
增加了
wide_to_long
面板数据便捷函数。参见文档。In [88]: np.random.seed(123) In [89]: df = pd.DataFrame({"A1970" : {0 : "a", 1 : "b", 2 : "c"}, ....: "A1980" : {0 : "d", 1 : "e", 2 : "f"}, ....: "B1970" : {0 : 2.5, 1 : 1.2, 2 : .7}, ....: "B1980" : {0 : 3.2, 1 : 1.3, 2 : .1}, ....: "X" : dict(zip(range(3), np.random.randn(3))) ....: }) ....: In [90]: df["id"] = df.index In [91]: df Out[91]: A1970 A1980 B1970 B1980 X id 0 a d 2.5 3.2 -1.085631 0 1 b e 1.2 1.3 0.997345 1 2 c f 0.7 0.1 0.282978 2 In [92]: pd.wide_to_long(df, ["A", "B"], i="id", j="year") Out[92]: X A B id year 0 1970 -1.085631 a 2.5 1 1970 0.997345 b 1.2 2 1970 0.282978 c 0.7 0 1980 -1.085631 d 3.2 1 1980 0.997345 e 1.3 2 1980 0.282978 f 0.1
-
to_csv
现在接受一个date_format
关键字参数,用于指定输出 datetime 对象的格式。索引、列和数值中遇到的日期时间对象都将应用此格式。(GH 4313) -
DataFrame.plot
通过传递kind='scatter'
参数,将 x 轴和 y 轴绘制成散点图(GH 2215) -
增加了对同时支持 v2 ID 的 Google Analytics v3 API 段 ID 的支持。(GH 5271)
实验性质
-
新的
eval()
函数使用numexpr
在后台实现表达式评估。这对涉及大型 DataFrame/Series 的复杂表达式会带来大幅加速。例如,In [93]: nrows, ncols = 20000, 100 In [94]: df1, df2, df3, df4 = [pd.DataFrame(np.random.randn(nrows, ncols)) ....: for _ in range(4)] ....:
# eval with NumExpr backend In [95]: %timeit pd.eval('df1 + df2 + df3 + df4') 2.82 ms +- 67.4 us per loop (mean +- std. dev. of 7 runs, 100 loops each)
# pure Python evaluation In [96]: %timeit df1 + df2 + df3 + df4 2.89 ms +- 56.9 us per loop (mean +- std. dev. of 7 runs, 100 loops each)
有关更多详细信息,请参阅文档。
-
与
pandas.eval
类似,DataFrame
增加了一个新的DataFrame.eval
方法,用于在DataFrame
的上下文中评估表达式。例如,In [97]: df = pd.DataFrame(np.random.randn(10, 2), columns=['a', 'b']) In [98]: df.eval('a + b') Out[98]: 0 -0.685204 1 1.589745 2 0.325441 3 -1.784153 4 -0.432893 5 0.171850 6 1.895919 7 3.065587 8 -0.092759 9 1.391365 dtype: float64
-
query()
方法已添加,允许您使用几乎与 Python 语法相同的自然查询语法选择DataFrame
的元素。例如,In [99]: n = 20 In [100]: df = pd.DataFrame(np.random.randint(n, size=(n, 3)), columns=['a', 'b', 'c']) In [101]: df.query('a < b < c') Out[101]: a b c 11 1 5 8 15 8 16 19
选择
df
中满足a < b < c
的所有行。更多详情请参见 文档。 -
pd.read_msgpack()
和pd.to_msgpack()
现在是序列化任意 pandas(和 python 对象)的支持方法,采用轻量级便携二进制格式。请参见 文档警告
由于这是一个实验性库,存储格式可能在未来版本中不稳定。
df = pd.DataFrame(np.random.rand(5, 2), columns=list('AB')) df.to_msgpack('foo.msg') pd.read_msgpack('foo.msg') s = pd.Series(np.random.rand(5), index=pd.date_range('20130101', periods=5)) pd.to_msgpack('foo.msg', df, s) pd.read_msgpack('foo.msg')
您可以将
iterator=True
传递给迭代解压后的结果for o in pd.read_msgpack('foo.msg', iterator=True): print(o)
-
pandas.io.gbq
提供了一种简单的方法,通过 pandas DataFrames 从 Google 的 BigQuery 数据集中提取数据,并加载数据。BigQuery 是一个高性能类似 SQL 的数据库服务,用于对极大数据集执行特定查询非常有用。请参见文档from pandas.io import gbq # A query to select the average monthly temperatures in the # in the year 2000 across the USA. The dataset, # publicata:samples.gsod, is available on all BigQuery accounts, # and is based on NOAA gsod data. query = """SELECT station_number as STATION, month as MONTH, AVG(mean_temp) as MEAN_TEMP FROM publicdata:samples.gsod WHERE YEAR = 2000 GROUP BY STATION, MONTH ORDER BY STATION, MONTH ASC""" # Fetch the result set for this query # Your Google BigQuery Project ID # To find this, see your dashboard: # https://console.developers.google.com/iam-admin/projects?authuser=0 projectid = 'xxxxxxxxx' df = gbq.read_gbq(query, project_id=projectid) # Use pandas to process and reshape the dataset df2 = df.pivot(index='STATION', columns='MONTH', values='MEAN_TEMP') df3 = pd.concat([df2.min(), df2.mean(), df2.max()], axis=1, keys=["Min Tem", "Mean Temp", "Max Temp"])
结果 DataFrame 为:
> df3 Min Tem Mean Temp Max Temp MONTH 1 -53.336667 39.827892 89.770968 2 -49.837500 43.685219 93.437932 3 -77.926087 48.708355 96.099998 4 -82.892858 55.070087 97.317240 5 -92.378261 61.428117 102.042856 6 -77.703334 65.858888 102.900000 7 -87.821428 68.169663 106.510714 8 -89.431999 68.614215 105.500000 9 -86.611112 63.436935 107.142856 10 -78.209677 56.880838 92.103333 11 -50.125000 48.861228 94.996428 12 -50.332258 42.286879 94.396774
警告
要使用此模块,您将需要一个 BigQuery 账户。有关详细信息,请参见 <
cloud.google.com/products/big-query
>。截至 10/10/13,Google 的 API 中存在一个 bug,阻止结果集超过 100,000 行。修补程序计划在 10/14/13 那周发布。 ## 内部重构
在 0.13.0 中进行了一次主要的重构,主要是将 Series
从 NDFrame
中子类化,这是目前 DataFrame
和 Panel
的基类,以统一方法和行为。Series 以前直接从 ndarray
子类化。 (GH 4080, GH 3862, GH 816)
警告
与 < 0.13.0 存在两个潜在的不兼容性
-
使用某些 numpy 函数以前会返回一个
Series
,如果将Series
作为参数传递。这似乎只影响np.ones_like
、np.empty_like
、np.diff
和np.where
。现在这些将返回ndarrays
。In [102]: s = pd.Series([1, 2, 3, 4])
Numpy 用法
In [103]: np.ones_like(s) Out[103]: array([1, 1, 1, 1]) In [104]: np.diff(s) Out[104]: array([1, 1, 1]) In [105]: np.where(s > 1, s, np.nan) Out[105]: array([nan, 2., 3., 4.])
Pandonic 用法
In [106]: pd.Series(1, index=s.index) Out[106]: 0 1 1 1 2 1 3 1 dtype: int64 In [107]: s.diff() Out[107]: 0 NaN 1 1.0 2 1.0 3 1.0 dtype: float64 In [108]: s.where(s > 1) Out[108]: 0 NaN 1 2.0 2 3.0 3 4.0 dtype: float64
-
直接将
Series
传递给期望ndarray
类型的 cython 函数将不再直接起作用,您必须传递Series.values
,请参见 性能增强 -
Series(0.5)
以前会返回标量0.5
,现在将返回一个包含 1 个元素的Series
-
此更改破坏了
rpy2<=2.3.8
。已针对 rpy2 提出了一个问题,并在 GH 5698 中详细介绍了解决方法。感谢 @JanSchulz。 -
保留了对 0.13 版本之前创建的 pickle 文件的兼容性。这些必须使用
pd.read_pickle
进行反序列化,请参见 Pickling。 -
重构 series.py/frame.py/panel.py,将通用代码移至 generic.py
-
在创建通用 NDFrame 结构时添加了
_setup_axes
-
移动了方法
-
from_axes,_wrap_array,axes,ix,loc,iloc,shape,empty,swapaxes,transpose,pop
-
__iter__,keys,__contains__,__len__,__neg__,__invert__
-
convert_objects,as_blocks,as_matrix,values
-
__getstate__,__setstate__
(frame/panel 中保留兼容性) -
__getattr__,__setattr__
-
_indexed_same,reindex_like,align,where,mask
-
fillna,replace
(Series
的 replace 现在与DataFrame
一致) -
filter
(还在不同轴上选择性过滤的情况下添加了轴参数) -
reindex,reindex_axis,take
-
truncate
(已移至NDFrame
的一部分)
-
-
-
这些是使
Panel
与DataFrame
更一致的 API 更改-
在指定相同轴的
Panel
上进行swapaxes
现在返回一个副本 -
支持属性访问以进行设置
-
filter 支持与原始
DataFrame
filter 相同的 API
-
-
使用无参数调用的 Reindex 现在将返回输入对象的副本
-
TimeSeries
现在是Series
的别名。属性is_time_series
可用于区分(如果需要) -
重构了使用 BlockManager 的稀疏对象
-
在 internals 中创建了一个新的块类型,
SparseBlock
,可以保存多种数据类型,并且不可合并。SparseSeries
和SparseDataFrame
现在从那里的层次结构(Series/DataFrame)继承更多方法,并且不再从SparseArray
继承(而是SparseBlock
的对象) -
稀疏套件现在支持与非稀疏数据的集成。支持非浮点稀疏数据(部分实现)
-
在 DataFrame 内部稀疏结构上的操作应保持稀疏性,合并类型操作将转换为密集(然后转换回稀疏),因此可能有些低效
-
为
SparseSeries
启用布尔/整数/切片的设置项 -
SparsePanels
的实现未更改(例如,不使用 BlockManager,需要工作)
-
-
为 Series/DataFrame 添加了
ftypes
方法,类似于dtypes
,但指示底层是稀疏的/密集的(以及 dtype) -
所有
NDFrame
对象现在可以使用__finalize__()
来指定从现有对象传播到新对象的各种值(例如,Series
中的name
现在将更自动地跟随) -
现在通过一套生成的类进行内部类型检查,允许
isinstance(value, klass)
而无需直接导入 klass,感谢@jtratner -
Series 更新中的错误,其中父框架未根据更改(GH 4080)或类型(GH 3217)更新其缓存,fillna(GH 3386)
-
重构
Series.reindex
到 core/generic.py(GH 4604,GH 4618),允许在 Series 上重新索引时使用method=
-
Series.copy
不再接受order
参数,现在与NDFrame
的复制一致 -
重构
rename
方法到 core/generic.py;修复了Series.rename
的问题(GH 4605),并为Panel
添加了相同签名的rename
-
将
clip
方法重构到 core/generic.py(GH 4798) -
将
_get_numeric_data/_get_bool_data
重构到 core/generic.py,允许 Series/Panel 功能 -
Series
(用于索引)/Panel
(用于项目)现在允许对其元素进行属性访问(GH 1903)In [109]: s = pd.Series([1, 2, 3], index=list('abc')) In [110]: s.b Out[110]: 2 In [111]: s.a = 5 In [112]: s Out[112]: a 5 b 2 c 3 dtype: int64 ``` ## Bug 修复
-
HDFStore
-
在追加时使用不同的块顺序引发无效的
TypeError
而不是ValueError
(GH 4096) -
read_hdf
没有遵守传递的mode
参数(GH 4504) -
添加一个长度为 0 的表将正常工作(GH 4273)
-
当传递
append
和table
两个参数时,to_hdf
会引发错误(GH 4584) -
从具有跨数据类型重复列的存储中读取将引发错误(GH 4767)
-
修复了当列名不是字符串时未正确引发
ValueError
的错误(GH 4956) -
以固定格式编写的零长度系列未正确反序列化(GH 4708)
-
修复了 pyt3 上的解码性能问题(GH 5441)
-
在存储之前验证 MultiIndex 中的级别(GH 5527)
-
正确处理带有 Panel 的
data_columns
(GH 5717)
-
-
修复了
tslib.tz_convert(vals, tz1, tz2)
中的错误:在尝试访问trans[pos + 1]
时可能会引发IndexError
异常(GH 4496) -
修复了
PeriodIndex.map
中的错误,使用str
会返回索引的字符串表示形式(GH 4136) -
使用自定义 matplotlib 默认颜色时,
test_time_series_plot_color_with_empty_kwargs
测试失败的问题已修复(GH 4345) -
修复了 stata IO 测试的运行。现在使用临时文件进行写入(GH 4353)
-
修复了
DataFrame.sum
比整数值框架的DataFrame.mean
慢的问题(GH 4365) -
read_html
测试现在与 Python 2.6 一起工作(GH 4351) -
修复了
network
测试抛出NameError
的错误,因为一个本地变量未定义(GH 4381) -
在
to_json
中,如果传递的orient
会因为重复索引而导致数据丢失,则引发异常(GH 4359) -
在
to_json
中,修复日期处理,使毫秒成为默认时间戳,如文档字符串所述(GH 4362) -
修复了 JSON NaT 处理问题,现在 NaT 被序列化为
null
(GH 4498) -
修复了 JSON 对象键中可转义字符的 JSON 处理方式(GH 4593)
-
修复了在
na_values=None
时传递keep_default_na=False
的问题(GH 4318) -
修复了在 DataFrame 具有重复列和混合 dtype 时,
values
引发错误的 bug,出现在(GH 4377) -
修复了在
read_json
中orient='split'
时重复列和类型转换的 bug(GH 4377) -
修复了 JSON 错误,其中具有除‘.’之外的小数分隔符的语言环境在编码/解码某些值时引发异常(GH 4918)
-
修复了使用
PeriodIndex
进行.iat
索引的问题(GH 4390) -
修复了
PeriodIndex
与自身连接时返回新实例而不是相同实例的问题(GH 4379);同时为其他索引类型添加了此测试 -
修复了使用 CSV cparser 和 usecols 参数时,所有 dtype 转换为对象的错误(GH 3192)
-
在合并块时修复了一个问题,导致结果 DataFrame 部分设置了 _ref_locs(GH 4403)
-
修复了使用顶级 matplotlib API 调用 hist 子图时被覆盖的问题(GH 4408)
-
解决了一个 py3 兼容性问题,即将字节表示为元组(GH 4455)
-
修复了 Panel 属性命名冲突问题,如果项目命名为‘a’(GH 3440)
-
修复了绘图时引发重复索引的问题(GH 4486)
-
修复了在
xs
中出现的 Panel 切片问题,返回的对象维度不正确(GH 4016) -
修复了使用转置框架进行的 Panel 赋值问题(GH 3830)
-
在使用 Panel 和 Panel 作为值需要对齐时,设置 Panel 索引会引发错误(GH 3777)
-
修复了对排序重复的 MultiIndex 进行排序时出现的问题,该 MultiIndex 具有多个数据类型(GH 4516)
-
修复了
DataFrame.set_values
中的错误,该错误导致在扩展索引时丢失名称属性(GH 3742,GH 4039) -
修复了可以在未经验证的情况下在
MultiIndex
上设置单个names
、levels
和labels
的问题(GH 3714,GH 4039) -
修复了在 pivot_table 中的问题(GH 3334)。如果值是索引,则无法计算边距。
-
修复了在与日期时间操作时具有
np.timedelta64
或np.offsets.DateOffset
的右侧值时出现的错误(GH 4532) -
修复了系列/日期时间索引和
np.timedelta64
进行算术运算时不起作用相同的问题(GH 4134)以及 NumPy 1.6 中的错误时间差(GH 4135) -
修复了在 Windows 平台上使用 PY3 时
pd.read_clipboard
中的错误([GH 4561](https://github.com/pandas-dev/pandas/issues/4561));解码不正确 -
如果代码参数超出范围,
tslib.get_period_field()
和tslib.get_period_field_arr()
现在会引发错误(GH 4519,GH 4520) -
修复了在空系列上进行布尔索引时丢失索引名称的问题(GH 4235),
infer_dtype
可以用于空数组。 -
修复了使用多个轴进行重新索引时的问题;如果轴匹配未替换当前轴,则可能导致可能的惰性频率推断问题(GH 3317)
-
修复
DataFrame.apply
错误地重新引发异常的问题(导致原始堆栈跟踪被截断)。 -
修复使用
ix/loc
和非唯一选择器进行选择的问题(GH 4619) -
修复使用 iloc/loc 进行赋值时涉及现有列中的 dtype 更改的问题(GH 4312,GH 5702)在核心/索引中使用 Block.setitem 的内部 setitem_with_indexer
-
修复 csv_import 中浮点数的千位运算符处理不正确的错误(GH 4322)
-
修复 CacheableOffset 未正确被许多 DateOffset 使用的问题;这阻止了 DateOffset 被缓存(GH 4609)
-
修复 DataFrame 在 lhs 上与列表/元组上的布尔比较的问题(GH 4576)
-
修复在
Series/DataFrame
上使用None
的 setitem 时的错误/ dtype 转换(GH 4667) -
根据传入的非默认编码修正
pd.read_stata
中的解码问题(GH 4626) -
修复
DataFrame.from_records
与普通ndarray
的问题(GH 4727) -
使用
iloc/loc
与横截面和重复索引存在错误(GH 4726) -
使用
to_csv
中的QUOTE_NONE
导致Exception
的错误(GH 4328) -
Series 索引不在右侧长度不正确时引发错误的错误已修复(GH 2702)
-
MultiIndexing 中存在部分字符串选择作为 MultIndex 的一部分的错误(GH 4758)
-
在具有非唯一索引的索引上重新索引现在将引发
ValueError
的错误(GH 4746) -
使用
loc/ix
设置具有 MultiIndex 轴和 NumPy 数组的单个索引器时存在错误,相关于(GH 3777) -
iloc
在切片索引失败时存在错误(GH 4771) -
在
read_fwf
中没有 colspecs 或 width 时显示不正确的错误消息(GH 4774) -
修复了在 Python 3 中使用
read_fwf
读取压缩文件的 bug。(GH 3963) -
修复了具有重复索引和 dtype 更改的赋值问题(GH 4686)
-
修复了在 Python 3 中读取压缩文件时将其作为
bytes
而不是str
的错误。简化了 Python 3 中生成字节文件处理的过程(GH 3963,GH 4785)。 -
修复了在不同版本的 matplotlib 中对数刻度条图中的 ticklocs/ticklabels 相关问题(GH 4789)
-
抑制了由 repr()发出的内部调用引发的 DeprecationWarning(GH 4391)
-
修复了具有重复索引和重复选择器的
.loc
中的问题(GH 4825) -
修复了
DataFrame.sort_index
中的问题,当按单个列排序并传递ascending
的列表时,ascending
参数被解释为True
(GH 4839,GH 4846) -
修复了
Panel.tshift
无法工作的问题。为Panel.shift
添加了freq
支持(GH 4853) -
修复了 TextFileReader 在 Python 引擎(即 PythonParser)中处理 thousands != “,”时的问题(GH 4596)
-
在使用 where 时,使用重复索引时 getitem 中的 bug(GH 4879)
-
修复了类型推断代码将浮点列强制转换为日期时间的问题(GH 4601)
-
修复了
_ensure_numeric
不检查复数的问题(GH 4902) -
修复了
convert_objects
对于> 2 维的 bug(GH 4937) -
修复了
FrozenNDArray
和FrozenList
的字符串方法(GH 4929) -
修复了在索引扩展场景中设置无效或超出范围值的 bug(GH 4940)
-
对空系列上的 fillna 进行测试(GH 4346), 感谢 @immerrr
-
修复了 Python 解析器中
read_csv
中的 skiprows 选项(GH 4382) -
修复了阻止
cut
与未显式传递标签的np.inf
级别一起工作的错误(GH 3415) -
修复了
DatetimeIndex.union
中重叠检查错误的问题(GH 4564) -
修复了 csv_parser 中千位分隔符和日期解析器之间的冲突问题(GH 4678)
-
在 dtypes 不相同时修复了追加的问题(显示混合 float/np.datetime64 的错误)(GH 4993)
-
修复了 DateOffset 的 repr。不再显示 kwds 中的重复条目。删除未使用的偏移字段。(GH 4638)
-
修复了在使用 usecols 时读取 csv 时错误的索引名称。仅适用于 c 解析器。(GH 4201)
-
Timestamp
对象现在可以出现在与Series
或DataFrame
对象的比较操作的左侧了(GH 4982). -
修复了使用
iloc/loc
通过np.nan
进行索引时的 bug(GH 5016) -
修复了低内存 c 解析器在同一文件的不同块中创建不同类型的错误的问题。现在强制转换为数值类型或引发警告。(GH 3866)
-
修复了将
Series
重塑为其自身形状时引发TypeError
的 bug(GH 4554)以及其他重塑问题。 -
修复了使用
ix/loc
和混合整数/字符串索引时的错误(GH 4544) -
确保系列-系列布尔比较是基于标签的(GH 4947)
-
在使用 Timestamp 部分索引器的多级索引中存在的 bug(GH 4294)
-
对构建全 nan 帧的 MultiIndex 进行测试/修复(GH 4078)
-
修复了
read_html()
未正确推断带有逗号的表的值的 bug(GH 5029) -
修复了
read_html()
在传递index_col=0
时解析不正确的错误(GH 5066) -
修复了
read_html()
错误推断标题类型的错误(GH 5048) -
修复了
DatetimeIndex
与PeriodIndex
连接导致堆栈溢出的错误(GH 3899) -
修复了
groupby
对象不允许绘图的错误(GH 5102) -
修复了
groupby
对象无法自动完成列名的错误(GH 5102) -
修复了
groupby.plot()
和相关函数多次复制图形的错误(GH 5102) -
在
fillna
上提供了object
类型的自动转换,相关(GH 5103) -
修复了在选项解析器清理中默认选项被覆盖的错误(GH 5121)
-
对于
iloc
索引使用列表/ndarray 的相同方式进行处理(GH 5006) -
修复了带有缺失值的
MultiIndex.get_level_values()
的错误(GH 5074) -
修复了使用 datetime64 输入的
Timestamp()
的边界检查错误(GH 4065) -
修复了
TestReadHtml
没有调用正确的read_html()
函数的错误(GH 5150) -
修复了
NDFrame.replace()
中的错误,使替换看起来像是(错误地)使用正则表达式(GH 5143) -
为
to_datetime
提供更好的错误消息(GH 4928) -
确保在 travis-ci 上测试不同的区域设置(GH 4918)。还添加了一些用于获取区域设置和使用上下文管理器设置区域设置的实用程序。
-
构造函数中的复合数据类型引发
NotImplementedError
(GH 5191) -
比较重复框架时存在错误(GH 4421)相关
-
在重复框架上的描述中存在错误
-
修复了带有格式和
coerce=True
的to_datetime
不引发异常的 bug (GH 5195) -
修复了在使用多个索引器和需要广播的 Series 作为 rhs 时,
loc
设置中的 bug (GH 5206) -
修复了在
MultiIndex
上设置级别或标签时不会清除缓存的values
属性,因此返回错误的values
的 bug。(GH 5215) -
修复了对分组的 DataFrame 或 Series 进行过滤时未保持原始顺序的 bug (GH 4621)。
-
修复了
Period
在工作日频率上始终向前滚动的 bug。(GH 5203) -
修复了 Excel 写入器中带有重复列名的框架未正确写入的 bug。(GH 5235)
-
修复了在 Series 上使用
drop
和非唯一索引时的 bug (GH 5248) -
修复了在文件中传递的名称多于列数导致 C 解析器中的段错误的 bug。(GH 5156)
-
修复了带有日期/时间类型的
Series.isin
的 bug (GH 5021) -
C 和 Python 解析器现在可以处理更常见的 MultiIndex 列格式,不需要为索引名称添加行。(GH 4702)
-
修复了尝试将越界日期用作对象 dtype 时的 bug (GH 5312)
-
修复了尝试显示嵌入的 PandasObject 时的 bug (GH 5324)
-
允许对 Timestamp 进行操作,如果结果超出边界,则返回一个 datetime 相关的 bug (GH 5312)
-
修复了
initObjToJSON()
的返回值/类型签名,以便与 numpy 的import_array()
兼容 (GH 5334, GH 5326) -
在 DataFrame 上重命名然后设置索引时的 bug (GH 5344)
-
测试套件在测试图形时不再保留临时文件。(GH 5347)(感谢 @yarikoptic 发现这个问题!)
-
修复了在 win32 上的 html 测试。(GH 4580)
-
确保
head/tail
基于iloc
,(GH 5370) -
修复了
PeriodIndex
字符串表示形��中存在 1 或 2 个元素时的 bug。(GH 5372) -
GroupBy 方法
transform
和filter
可以用于具有重复(非唯一)索引的 Series 和 DataFrames。(GH 4620) -
修复了空系列在 repr 中未打印名称的问题(GH 4651)
-
默认情况下,使测试在临时目录中创建临时文件。(GH 5419)
-
标量的
pd.to_timedelta
返回一个标量(GH 5410) -
pd.to_timedelta
接受NaN
和NaT
,返回NaT
而不是引发异常(GH 5437) -
在较大尺寸的 pandas 对象上对
isnull
进行性能改进 -
修复了各种与 1d ndarray 不匹配长度的 setitem 问题(GH 5508)
-
使用 MultiIndex 和
iloc
时,getitem 存在 bug(GH 5528) -
在 Series 上进行 delitem 存在 bug(GH 5542)
-
使用自定义函数时,在 apply 中存在 bug,且对象未被改变(GH 5545)
-
使用
loc
从非唯一索引中选择时存在 bug(GH 5553) -
当用户函数返回
None
时,groupby 返回非一致类型存在 bug,(GH 5592) -
解决了 numpy 1.7.0 中的回归问题,该问题错误地从
ndarray.item
引发 IndexError(GH 5666) -
对具有非唯一索引的对象进行重复索引存在 bug(GH 5678)
-
使用 Series 和传递的 series/dict 时的 fillna 问题修复(GH 5703)
-
在具有类似日期时间的分组器的 groupby transform 中存在错误(GH 5712)
-
使用某些键时,PY3 中 MultiIndex 选择存在错误(GH 5725)
-
在某些情况下,不同 dtype 的行连接失败(GH 5754) ## 贡献者
总共有 77 人为此版本贡献了补丁。名字后面带有“+”的人第一次贡献了补丁。
-
阿古斯丁·赫兰斯 +
-
亚历克斯·高迪 +
-
亚历克斯·罗斯伯格 +
-
安德烈亚斯·克洛斯特曼 +
-
安德烈亚斯·武尔 +
-
安迪·海登
-
本·亚历克斯 +
-
本尼迪克特·索尔 +
-
布拉德·布兰
-
凯勒布·爱普斯坦 +
-
张舍
-
克里斯托弗·惠兰
-
DSM +
-
戴尔·郑 +
-
丹·伯肯
-
大卫·拉什 +
-
迪特·范登布斯切
-
加比·达瓦 +
-
加勒特·德拉帕拉
-
戈约 +
-
格雷格·雷达 +
-
伊万·斯米尔诺夫 +
-
杰克·凯利 +
-
雅各布·谢尔 +
-
扬·舒尔茨 +
-
杰夫·特拉特纳
-
杰弗里·特拉特纳
-
约翰·麦克纳马拉 +
-
约翰·W·奥布莱恩 +
-
乔里斯·范丹博斯切
-
贾斯汀·博佐尼尔 +
-
凯尔西·乔达尔
-
凯文·斯通
-
基兰·奥马霍尼
-
凯尔·豪斯曼 +
-
凯尔·凯利 +
-
凯尔·迈耶
-
迈克·凯利
-
莫塔达·梅希亚 +
-
尼克·福蒂 +
-
奥利维尔·哈里斯 +
-
安德烈·切尔蒂克 +
-
PKEuS
-
菲利普·克劳德
-
皮埃尔·哈西格 +
-
理查德·T·盖伊 +
-
罗曼·佩卡尔 +
-
罗伊·韩贤晋
-
斯基普·西博尔德
-
斯滕 +
-
托马斯·A·卡斯韦尔 +
-
托马斯·克卢伊弗
-
蒂亚戈·雷克奎霍 +
-
汤姆奥古斯伯格
-
特伦特·豪克
-
瓦伦丁·哈内尔 +
-
Viktor Kerkez +
-
Vincent Arel-Bundock
-
Wes McKinney
-
Wes Turner +
-
Weston Renoud +
-
Yaroslav Halchenko
-
Zach Dwiel +
-
chapman siu +
-
chappers +
-
d10genes +
-
danielballan
-
daydreamt +
-
engstrom +
-
jreback
-
monicaBee +
-
prossahl +
-
rockg +
-
unutbu +
-
westurner +
-
y-p
-
zach powers
API 变更
-
read_excel
现在支持在其sheetname
参数中传入整数,以读取指定索引的工作表(GH 4301)。 -
文本解析器现在将任何类似于 inf(“inf”,“Inf”,“-Inf”,“iNf”等)的内容视为无穷大。(GH 4220, GH 4219),影响
read_table
,read_csv
等。 -
pandas
现在在不需要 2to3 的情况下兼容 Python 2/3,感谢 @jtratner。因此,pandas 现在更广泛地使用迭代器。这也导致将 Benjamin Peterson 的six
库的实质部分引入 compat。(GH 4384, GH 4375, GH 4372) -
pandas.util.compat
和pandas.util.py3compat
已合并为pandas.compat
。pandas.compat
现在包含许多函数,允许 2/3 兼容性。它包含 range、filter、map 和 zip 的列表和迭代器版本,以及其他必要的元素,以实现 Python 3 的兼容性。lmap
、lzip
、lrange
和lfilter
都生成列表而不是迭代器,以与numpy
、下标和pandas
构造函数兼容。(GH 4384, GH 4375, GH 4372) -
使用负索引器的
Series.get
现在返回与[]
相同的结果 (GH 4390) -
更改了
Index
和MultiIndex
处理元数据(levels
、labels
和names
)的方式 (GH 4039)# previously, you would have set levels or labels directly >>> pd.index.levels = [[1, 2, 3, 4], [1, 2, 4, 4]] # now, you use the set_levels or set_labels methods >>> index = pd.index.set_levels([[1, 2, 3, 4], [1, 2, 4, 4]]) # similarly, for names, you can rename the object # but setting names is not deprecated >>> index = pd.index.set_names(["bob", "cranberry"]) # and all methods take an inplace kwarg - but return None >>> pd.index.set_names(["bob", "cranberry"], inplace=True)
-
所有 与
NDFrame
对象的除法现在都是 truedivision,无论未来的导入如何。这意味着对 pandas 对象进行操作将默认使用 浮点数 除法,并返回浮点数 dtype。您可以使用//
和floordiv
进行整数除法。整数除法
In [3]: arr = np.array([1, 2, 3, 4]) In [4]: arr2 = np.array([5, 3, 2, 1]) In [5]: arr / arr2 Out[5]: array([0, 0, 1, 4]) In [6]: pd.Series(arr) // pd.Series(arr2) Out[6]: 0 0 1 0 2 1 3 4 dtype: int64
真除法
In [7]: pd.Series(arr) / pd.Series(arr2) # no future import required Out[7]: 0 0.200000 1 0.666667 2 1.500000 3 4.000000 dtype: float64
-
如果将
downcast='infer'
传递给fillna/ffill/bfill
,则推断并降级 dtype (GH 4604) -
__nonzero__
对所有 NDFrame 对象,现在将引发ValueError
,这恢复了 (GH 1073, GH 4633) 的行为。有关更详细的讨论,请参见 注意事项。这样可以防止对 整个 pandas 对象进行布尔比较,这在本质上是模棱两���的。所有这些都将引发
ValueError
。>>> df = pd.DataFrame({'A': np.random.randn(10), ... 'B': np.random.randn(10), ... 'C': pd.date_range('20130101', periods=10) ... }) ... >>> if df: ... pass ... Traceback (most recent call last): ... ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). >>> df1 = df >>> df2 = df >>> df1 and df2 Traceback (most recent call last): ... ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). >>> d = [1, 2, 3] >>> s1 = pd.Series(d) >>> s2 = pd.Series(d) >>> s1 and s2 Traceback (most recent call last): ... ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
在
NDFrame
对象中添加了.bool()
方法,以便于评估单个元素的布尔序列:>>> pd.Series([True]).bool() True >>> pd.Series([False]).bool() False >>> pd.DataFrame([[True]]).bool() True >>> pd.DataFrame([[False]]).bool() False
-
所有非索引 NDFrames(
Series
,DataFrame
,Panel
,Panel4D
,SparsePanel
等)现在都支持整套算术运算符和算术灵活方法(add,sub,mul 等)。SparsePanel
不支持非标量的pow
或mod
。 (GH 3765) -
现在
Series
和DataFrame
有一个mode()
方法,可以按轴/序列计算统计模式。 (GH 5367) -
现在默认情况下,如果用户正在向副本赋值,则链式赋值将发出警告。这可以通过选项
mode.chained_assignment
进行更改,允许的选项是raise/warn/None
。请参阅文档。In [1]: dfc = pd.DataFrame({'A': ['aaa', 'bbb', 'ccc'], 'B': [1, 2, 3]}) In [2]: pd.set_option('chained_assignment', 'warn')
如果尝试这样做,将显示以下警告/异常。
In [3]: dfc.loc[0]['A'] = 1111
Traceback (most recent call last) ... SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_index,col_indexer] = value instead
这是正确的分配方法。
In [4]: dfc.loc[0, 'A'] = 11 In [5]: dfc Out[5]: A B 0 11 1 1 bbb 2 2 ccc 3
-
Panel.reindex
具有以下调用签名Panel.reindex(items=None, major_axis=None, minor_axis=None, **kwargs)
以符合其他
NDFrame
对象。有关更多信息,请参见内部重构。 -
Series.argmin
和Series.argmax
现在别名为Series.idxmin
和Series.idxmax
。这些返回索引的分别是最小或最大元素的位置。在 0.13.0 版本之前,这些将返回最小/最大元素的位置。 (GH 6214)
先前版本的废弃/更改
这些是在 0.12 版本或之前宣布的更改,在 0.13.0 版本生效。
-
移除了废弃的
Factor
(GH 3650) -
移除了废弃的
set_printoptions/reset_printoptions
(GH 3046) -
移除了废弃的
_verbose_info
(GH 3215) -
从
pandas.io.parsers
中删除了废弃的read_clipboard/to_clipboard/ExcelFile/ExcelWriter
(GH 3717)这些函数在主要的 pandas 命名空间中可用(例如pd.read_clipboard
) -
对于
to_csv
和read_csv
,tupleize_cols
的默认值现在都是False
。在 0.12 版本中提出了公平警告(GH 3604) -
display.max_seq_len
的默认值现在是 100 而不是None
。这将在各个地方激活长序列的截断显示(“…”)。 (GH 3391)
弃用
在 0.13.0 版本中已弃用
-
废弃了
iterkv
,将在将来的版本中删除(这是 iteritems 的别名,用于绕过2to3
的更改)。 (GH 4384, GH 4375, GH 4372) -
弃用了字符串方法
match
,其作用现在更符合习惯的是extract
。在将来的版本中,match
的默认行为将更改为类似于contains
,它返回一个布尔索引器。(它们的区别在于严格性:match
依赖于re.match
,而contains
依赖于re.search
。)在此版本中,弃用的行为是默认的,但新行为可以通过关键字参数as_indexer=True
获得。
索引 API 更改
在 0.13 之前,无法使用标签索引器(.loc/.ix
)设置不包含在特定轴索引中的值。(GH 2578)。请参阅文档
在Series
情况下,这实际上是一个追加操作。
In [6]: s = pd.Series([1, 2, 3])
In [7]: s
Out[7]:
0 1
1 2
2 3
dtype: int64
In [8]: s[5] = 5.
In [9]: s
Out[9]:
0 1.0
1 2.0
2 3.0
5 5.0
dtype: float64
In [10]: dfi = pd.DataFrame(np.arange(6).reshape(3, 2),
....: columns=['A', 'B'])
....:
In [11]: dfi
Out[11]:
A B
0 0 1
1 2 3
2 4 5
以前会出现KeyError
。
In [12]: dfi.loc[:, 'C'] = dfi.loc[:, 'A']
In [13]: dfi
Out[13]:
A B C
0 0 1 0
1 2 3 2
2 4 5 4
这就像一个append
操作。
In [14]: dfi.loc[3] = 5
In [15]: dfi
Out[15]:
A B C
0 0 1 0
1 2 3 2
2 4 5 4
3 5 5 5
在任意轴上进行的 Panel 设置操作将使输入与 Panel 对齐。
In [20]: p = pd.Panel(np.arange(16).reshape(2, 4, 2),
....: items=['Item1', 'Item2'],
....: major_axis=pd.date_range('2001/1/12', periods=4),
....: minor_axis=['A', 'B'], dtype='float64')
....:
In [21]: p
Out[21]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 4 (major_axis) x 2 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis: 2001-01-12 00:00:00 to 2001-01-15 00:00:00
Minor_axis axis: A to B
In [22]: p.loc[:, :, 'C'] = pd.Series([30, 32], index=p.items)
In [23]: p
Out[23]:
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 4 (major_axis) x 3 (minor_axis)
Items axis: Item1 to Item2
Major_axis axis: 2001-01-12 00:00:00 to 2001-01-15 00:00:00
Minor_axis axis: A to C
In [24]: p.loc[:, :, 'C']
Out[24]:
Item1 Item2
2001-01-12 30.0 32.0
2001-01-13 30.0 32.0
2001-01-14 30.0 32.0
2001-01-15 30.0 32.0
Float64Index API 更改
-
添加了新的索引类型,
Float64Index
。当在索引创建中传递浮点值时,将自动创建此类型。这使得基于纯标签的切片范式成为可能,使得[],ix,loc
用于标量索引和切片的工作方式完全相同。(GH 263)默认情况下构造是针对浮点类型值的。
In [16]: index = pd.Index([1.5, 2, 3, 4.5, 5]) In [17]: index Out[17]: Index([1.5, 2.0, 3.0, 4.5, 5.0], dtype='float64') In [18]: s = pd.Series(range(5), index=index) In [19]: s Out[19]: 1.5 0 2.0 1 3.0 2 4.5 3 5.0 4 dtype: int64
对于
[],.ix,.loc
的标量选择将始终基于标签。整数将匹配相等的浮点索引(例如,3
等同于3.0
)。In [20]: s[3] Out[20]: 2 In [21]: s.loc[3] Out[21]: 2
唯一的位置索引是通过
iloc
进行的。In [22]: s.iloc[3] Out[22]: 3
未找到的标量索引将引发
KeyError
。切片始终是在索引的值上进行的,对于
[],ix,loc
始终是位置性的,对于iloc
始终是位置性的。In [23]: s[2:4] Out[23]: 2.0 1 3.0 2 dtype: int64 In [24]: s.loc[2:4] Out[24]: 2.0 1 3.0 2 dtype: int64 In [25]: s.iloc[2:4] Out[25]: 3.0 2 4.5 3 dtype: int64
在浮点索引中,允许使用浮点数进行切片。
In [26]: s[2.1:4.6] Out[26]: 3.0 2 4.5 3 dtype: int64 In [27]: s.loc[2.1:4.6] Out[27]: 3.0 2 4.5 3 dtype: int64
-
其他索引类型的索引保留(并对
[],ix
进行位置回退),唯一的例外是,在非Float64Index
上的浮点数切片索引现在会引发TypeError
。In [1]: pd.Series(range(5))[3.5] TypeError: the label [3.5] is not a proper indexer for this index type (Int64Index) In [1]: pd.Series(range(5))[3.5:4.5] TypeError: the slice start [3.5] is not a proper indexer for this index type (Int64Index)
在将来的版本中,将弃用使用标量浮点索引器,但目前允许使用。
In [3]: pd.Series(range(5))[3.0] Out[3]: 3
HDFStore API 更改
-
查询格式更改。现在支持更类似字符串的查询格式。请参阅文档。
In [28]: path = 'test.h5' In [29]: dfq = pd.DataFrame(np.random.randn(10, 4), ....: columns=list('ABCD'), ....: index=pd.date_range('20130101', periods=10)) ....: In [30]: dfq.to_hdf(path, key='dfq', format='table', data_columns=True)
使用布尔表达式,进行内联函数评估。
In [31]: pd.read_hdf(path, 'dfq', ....: where="index>Timestamp('20130104') & columns=['A', 'B']") ....: Out[31]: A B 2013-01-05 -0.424972 0.567020 2013-01-06 -0.673690 0.113648 2013-01-07 0.404705 0.577046 2013-01-08 -0.370647 -1.157892 2013-01-09 1.075770 -0.109050 2013-01-10 0.357021 -0.674600
使用内联列引用
In [32]: pd.read_hdf(path, 'dfq', ....: where="A>0 or C>0") ....: Out[32]: A B C D 2013-01-01 0.469112 -0.282863 -1.509059 -1.135632 2013-01-02 1.212112 -0.173215 0.119209 -1.044236 2013-01-04 0.721555 -0.706771 -1.039575 0.271860 2013-01-05 -0.424972 0.567020 0.276232 -1.087401 2013-01-07 0.404705 0.577046 -1.715002 -1.039268 2013-01-09 1.075770 -0.109050 1.643563 -1.469388 2013-01-10 0.357021 -0.674600 -1.776904 -0.968914
-
format
关键字现在替换了table
关键字;允许的值为fixed(f)
或table(t)
,与<0.13.0 之前的默认值相同,例如put
意味着fixed
格式,append
意味着table
格式。可以通过设置io.hdf.default_format
选项来设置此默认格式。In [33]: path = 'test.h5' In [34]: df = pd.DataFrame(np.random.randn(10, 2)) In [35]: df.to_hdf(path, key='df_table', format='table') In [36]: df.to_hdf(path, key='df_table2', append=True) In [37]: df.to_hdf(path, key='df_fixed') In [38]: with pd.HDFStore(path) as store: ....: print(store) ....: <class 'pandas.io.pytables.HDFStore'> File path: test.h5
-
显著的表写入性能改进
-
处理以表格格式传递的
Series
(GH 4330) -
现在可以在表格中序列化
timedelta64[ns]
数据类型(GH 3577),请参阅文档。 -
添加了一个
is_open
属性,用于指示底层文件句柄是否打开;当查看存储时,关闭的存储现在将报告“CLOSED”(而不是引发错误)(GH 4409) -
现在关闭
HDFStore
将关闭该HDFStore
实例,但只有在所有打开句柄的引用计数(由PyTables
)为 0 时才会关闭实际文件。基本上,您有一个由变量引用的本地HDFStore
实例。一旦关闭,它将报告已关闭。其他引用(指向同一文件)将继续操作,直到它们自己关闭。对已关闭文件执行操作将引发ClosedFileError
In [39]: path = 'test.h5' In [40]: df = pd.DataFrame(np.random.randn(10, 2)) In [41]: store1 = pd.HDFStore(path) In [42]: store2 = pd.HDFStore(path) In [43]: store1.append('df', df) In [44]: store2.append('df2', df) In [45]: store1 Out[45]: <class 'pandas.io.pytables.HDFStore'> File path: test.h5 In [46]: store2 Out[46]: <class 'pandas.io.pytables.HDFStore'> File path: test.h5 In [47]: store1.close() In [48]: store2 Out[48]: <class 'pandas.io.pytables.HDFStore'> File path: test.h5 In [49]: store2.close() In [50]: store2 Out[50]: <class 'pandas.io.pytables.HDFStore'> File path: test.h5
-
删除了
_quiet
属性,如果从表中检索重复行,则替换为DuplicateWarning
(GH 4367) -
从
open
中删除了warn
参数。如果尝试使用mode='w'
与打开的文件句柄,则将引发PossibleDataLossError
异常(GH 4367) -
允许传递位置数组或掩码作为
where
条件(GH 4467)。请参阅文档以获取示例。 -
将关键字
dropna=True
添加到append
中,以更改是否不将所有 nan 行写入存储(默认为True
,不写入所有 nan 行),也可通过选项io.hdf.dropna_table
进行设置(GH 4625) -
通过存储创建参数传递;可用于支持内存存储
DataFrame repr 更改
HTML 和纯文本表示的DataFrame
现在在表格超过一定大小时显示截断视图,而不是切换到简短信息视图(GH 4886, GH 5550)。这使表示更加一致,因为小的 DataFrames 变得更大。
要获取信息视图,请调用DataFrame.info()
。如果您更喜欢信息视图作为大 DataFrames 的 repr,可以通过运行 set_option('display.large_repr', 'info')
来设置。
增强功能
-
df.to_clipboard()
学会了一个新的excel
关键字,让您可以直接将 df 数据粘贴到 excel 中(默认启用)。(GH 5070). -
read_html
现在引发URLError
而不是捕获并引发ValueError
(GH 4303, GH 4305) -
添加了对
read_clipboard()
和to_clipboard()
的测试(GH 4282) -
剪贴板功能现在支持 PySide (GH 4282)
-
当绘图参数包含重叠的颜色和样式参数时,添加了更具信息性的错误消息 (GH 4402)
-
to_dict
现在接受records
作为可能的输出类型。返回一个以列键为字典的数组。 (GH 4936) -
get_dummies
中的NaN
处理 (GH 4446) 使用dummy_na
# previously, nan was erroneously counted as 2 here # now it is not counted at all In [51]: pd.get_dummies([1, 2, np.nan]) Out[51]: 1.0 2.0 0 True False 1 False True 2 False False # unless requested In [52]: pd.get_dummies([1, 2, np.nan], dummy_na=True) Out[52]: 1.0 2.0 NaN 0 True False False 1 False True False 2 False False True
-
timedelta64[ns]
操作。请参阅文档。警告
大多数这些操作需要
numpy >= 1.7
使用新的顶级
to_timedelta
,您可以将标准时间增量格式(由to_csv
生成)的标量或数组转换为时间增量类型(np.timedelta64
中的nanoseconds
)。In [53]: pd.to_timedelta('1 days 06:05:01.00003') Out[53]: Timedelta('1 days 06:05:01.000030') In [54]: pd.to_timedelta('15.5us') Out[54]: Timedelta('0 days 00:00:00.000015500') In [55]: pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan']) Out[55]: TimedeltaIndex(['1 days 06:05:01.000030', '0 days 00:00:00.000015500', NaT], dtype='timedelta64[ns]', freq=None) In [56]: pd.to_timedelta(np.arange(5), unit='s') Out[56]: TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:01', '0 days 00:00:02', '0 days 00:00:03', '0 days 00:00:04'], dtype='timedelta64[ns]', freq=None) In [57]: pd.to_timedelta(np.arange(5), unit='d') Out[57]: TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'], dtype='timedelta64[ns]', freq=None)
一个
timedelta64[ns]
dtype 的 Series 现在可以被另一个timedelta64[ns]
对象除以,或者转换为float64
dtype 的 Series。这是频率转换。请参阅文档。In [58]: import datetime In [59]: td = pd.Series(pd.date_range('20130101', periods=4)) - pd.Series( ....: pd.date_range('20121201', periods=4)) ....: In [60]: td[2] += np.timedelta64(datetime.timedelta(minutes=5, seconds=3)) In [61]: td[3] = np.nan In [62]: td Out[62]: 0 31 days 00:00:00 1 31 days 00:00:00 2 31 days 00:05:03 3 NaT dtype: timedelta64[ns]
# to days In [63]: td / np.timedelta64(1, 'D') Out[63]: 0 31.000000 1 31.000000 2 31.003507 3 NaN dtype: float64 In [64]: td.astype('timedelta64[D]') Out[64]: 0 31.0 1 31.0 2 31.0 3 NaN dtype: float64 # to seconds In [65]: td / np.timedelta64(1, 's') Out[65]: 0 2678400.0 1 2678400.0 2 2678703.0 3 NaN dtype: float64 In [66]: td.astype('timedelta64[s]') Out[66]: 0 2678400.0 1 2678400.0 2 2678703.0 3 NaN dtype: float64
将
timedelta64[ns]
Series 除以整数或整数 Series,或乘以整数In [63]: td * -1 Out[63]: 0 -31 days +00:00:00 1 -31 days +00:00:00 2 -32 days +23:54:57 3 NaT dtype: timedelta64[ns] In [64]: td * pd.Series([1, 2, 3, 4]) Out[64]: 0 31 days 00:00:00 1 62 days 00:00:00 2 93 days 00:15:09 3 NaT dtype: timedelta64[ns]
绝对
DateOffset
对象可以等效于timedeltas
In [65]: from pandas import offsets In [66]: td + offsets.Minute(5) + offsets.Milli(5) Out[66]: 0 31 days 00:05:00.005000 1 31 days 00:05:00.005000 2 31 days 00:10:03.005000 3 NaT dtype: timedelta64[ns]
现在支持对时间增量的
fillna
In [67]: td.fillna(pd.Timedelta(0)) Out[67]: 0 31 days 00:00:00 1 31 days 00:00:00 2 31 days 00:05:03 3 0 days 00:00:00 dtype: timedelta64[ns] In [68]: td.fillna(datetime.timedelta(days=1, seconds=5)) Out[68]: 0 31 days 00:00:00 1 31 days 00:00:00 2 31 days 00:05:03 3 1 days 00:00:05 dtype: timedelta64[ns]
您可以对时间增量进行数值缩减操作。
In [69]: td.mean() Out[69]: Timedelta('31 days 00:01:41') In [70]: td.quantile(.1) Out[70]: Timedelta('31 days 00:00:00')
-
plot(kind='kde')
现在接受可选参数bw_method
和ind
,传递给 scipy.stats.gaussian_kde()(对于 scipy >= 0.11.0)以设置带宽,并传递给 gkde.evaluate() 以指定评估的索引。请参阅 scipy 文档。 (GH 4298) -
DataFrame 构造函数现在接受 numpy 掩码记录数组 (GH 3478)
-
新的矢量化字符串方法
extract
更方便地返回正则表达式匹配。In [71]: pd.Series(['a1', 'b2', 'c3']).str.extract('ab') Out[71]: 0 0 1 1 2 2 NaN
不匹配的元素返回
NaN
。提取具有多个组的正则表达式将返回一个每组一列的 DataFrame。In [72]: pd.Series(['a1', 'b2', 'c3']).str.extract('([ab])(\\d)') Out[72]: 0 1 0 a 1 1 b 2 2 NaN NaN
不匹配的元素返回一行
NaN
。因此,一系列混乱的字符串可以转换为具有相同索引的清理或更有用的字符串的 Series 或 DataFrame,而无需使用get()
来访问元组或re.match
对象。命名组如
In [73]: pd.Series(['a1', 'b2', 'c3']).str.extract( ....: '(?P<letter>[ab])(?P<digit>\\d)') ....: Out[73]: letter digit 0 a 1 1 b 2 2 NaN NaN
还可以使用可选组。
In [74]: pd.Series(['a1', 'b2', '3']).str.extract( ....: '(?P<letter>[ab])?(?P<digit>\\d)') ....: Out[74]: letter digit 0 a 1 1 b 2 2 NaN 3
-
read_stata
现在接受 Stata 13 格式 (GH 4291) -
如果数据具有正确分隔和正确对齐列,并使用提供给函数的分隔符,
read_fwf
现在可以从文件的前 100 行推断列规范 (GH 4488)。 -
支持纳秒时间作为偏移量
警告
这些操作需要
numpy >= 1.7
秒及以下范围内的周期转换已经重新设计并扩展到纳秒。现在可以使用纳秒范围的周期。
In [79]: pd.date_range('2013-01-01', periods=5, freq='5N') Out[79]: DatetimeIndex([ '2013-01-01 00:00:00', '2013-01-01 00:00:00.000000005', '2013-01-01 00:00:00.000000010', '2013-01-01 00:00:00.000000015', '2013-01-01 00:00:00.000000020'], dtype='datetime64[ns]', freq='5N')
或者使用频率作为偏移量
In [75]: pd.date_range('2013-01-01', periods=5, freq=pd.offsets.Nano(5)) Out[75]: DatetimeIndex([ '2013-01-01 00:00:00', '2013-01-01 00:00:00.000000005', '2013-01-01 00:00:00.000000010', '2013-01-01 00:00:00.000000015', '2013-01-01 00:00:00.000000020'], dtype='datetime64[ns]', freq='5ns')
时间戳可以在纳秒范围内进行修改
In [76]: t = pd.Timestamp('20130101 09:01:02') In [77]: t + pd.tseries.offsets.Nano(123) Out[77]: Timestamp('2013-01-01 09:01:02.000000123')
-
DataFrames 的新方法
isin
,与布尔索引很好地配合。isin
的参数,我们要将 DataFrame 与之进行比较的内容,可以是 DataFrame、Series、dict 或值数组。更多信息请参阅文档。要获取满足任何条件的行:
In [78]: dfi = pd.DataFrame({'A': [1, 2, 3, 4], 'B': ['a', 'b', 'f', 'n']}) In [79]: dfi Out[79]: A B 0 1 a 1 2 b 2 3 f 3 4 n In [80]: other = pd.DataFrame({'A': [1, 3, 3, 7], 'B': ['e', 'f', 'f', 'e']}) In [81]: mask = dfi.isin(other) In [82]: mask Out[82]: A B 0 True False 1 False False 2 True True 3 False False In [83]: dfi[mask.any(axis=1)] Out[83]: A B 0 1 a 2 3 f
-
Series
现在支持to_frame
方法,将其转换为单列 DataFrame(GH 5164) -
所有列在这里列出的 R 数据集
stat.ethz.ch/R-manual/R-devel/library/datasets/html/00Index.html
现在可以加载到 pandas 对象中# note that pandas.rpy was deprecated in v0.16.0 import pandas.rpy.common as com com.load_data('Titanic')
-
tz_localize
可以根据未本地化数据的结构推断秋季日光节约时间转换(GH 4230),请参阅文档 -
DatetimeIndex
现在在 API 文档中,参见文档 -
json_normalize()
是一个新方法,允许您从半结构化的 JSON 数据创建一个扁平表。请参阅文档(GH 1067) -
为 qtpandas 的 DataFrameModel 和 DataFrameWidget 添加了 PySide 支持。
-
Python csv 解析器现在支持 usecols(GH 4335)
-
频率增加了几个新的偏移量:
-
DataFrame 现在有一个新的
interpolate
方法,类似于 Series(GH 4434,GH 1892)In [84]: df = pd.DataFrame({'A': [1, 2.1, np.nan, 4.7, 5.6, 6.8], ....: 'B': [.25, np.nan, np.nan, 4, 12.2, 14.4]}) ....: In [85]: df.interpolate() Out[85]: A B 0 1.0 0.25 1 2.1 1.50 2 3.4 2.75 3 4.7 4.00 4 5.6 12.20 5 6.8 14.40
此外,
interpolate
的method
参数已扩展到包括'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'barycentric', 'krogh', 'piecewise_polynomial', 'pchip', 'polynomial', 'spline'
。新方法需要scipy。有关各种方法何时适用的更多信息,请参阅 Scipy 参考指南和文档。请参阅文档。Interpolate 现在还接受一个
limit
关键字参数。这与fillna
的限制类似:In [86]: ser = pd.Series([1, 3, np.nan, np.nan, np.nan, 11]) In [87]: ser.interpolate(limit=2) Out[87]: 0 1.0 1 3.0 2 5.0 3 7.0 4 NaN 5 11.0 dtype: float64
-
添加了
wide_to_long
面板数据便利函数。请参阅文档。In [88]: np.random.seed(123) In [89]: df = pd.DataFrame({"A1970" : {0 : "a", 1 : "b", 2 : "c"}, ....: "A1980" : {0 : "d", 1 : "e", 2 : "f"}, ....: "B1970" : {0 : 2.5, 1 : 1.2, 2 : .7}, ....: "B1980" : {0 : 3.2, 1 : 1.3, 2 : .1}, ....: "X" : dict(zip(range(3), np.random.randn(3))) ....: }) ....: In [90]: df["id"] = df.index In [91]: df Out[91]: A1970 A1980 B1970 B1980 X id 0 a d 2.5 3.2 -1.085631 0 1 b e 1.2 1.3 0.997345 1 2 c f 0.7 0.1 0.282978 2 In [92]: pd.wide_to_long(df, ["A", "B"], i="id", j="year") Out[92]: X A B id year 0 1970 -1.085631 a 2.5 1 1970 0.997345 b 1.2 2 1970 0.282978 c 0.7 0 1980 -1.085631 d 3.2 1 1980 0.997345 e 1.3 2 1980 0.282978 f 0.1
-
to_csv
现在接受一个date_format
关键字参数,指定输出日期时间对象的格式。索引、列和值中遇到的日期时间都将应用此格式。(GH 4313) -
DataFrame.plot
将通过传递kind='scatter'
来绘制 x 与 y 的散点图。(GH 2215) -
增加了对支持 Google Analytics v3 API 段 ID 的支持,也支持 v2 ID。(GH 5271)
实验性
-
新的
eval()
函数实现了使用numexpr
在后台进行表达式评估。这将大大加快涉及大型 DataFrame/Series 的复杂表达式的速度。例如,In [93]: nrows, ncols = 20000, 100 In [94]: df1, df2, df3, df4 = [pd.DataFrame(np.random.randn(nrows, ncols)) ....: for _ in range(4)] ....:
# eval with NumExpr backend In [95]: %timeit pd.eval('df1 + df2 + df3 + df4') 2.82 ms +- 67.4 us per loop (mean +- std. dev. of 7 runs, 100 loops each)
# pure Python evaluation In [96]: %timeit df1 + df2 + df3 + df4 2.89 ms +- 56.9 us per loop (mean +- std. dev. of 7 runs, 100 loops each)
有关更多详细信息,请参阅文档
-
与
pandas.eval
类似,DataFrame
现在有一个新的DataFrame.eval
方法,用于在DataFrame
的上下文中评估表达式。例如,In [97]: df = pd.DataFrame(np.random.randn(10, 2), columns=['a', 'b']) In [98]: df.eval('a + b') Out[98]: 0 -0.685204 1 1.589745 2 0.325441 3 -1.784153 4 -0.432893 5 0.171850 6 1.895919 7 3.065587 8 -0.092759 9 1.391365 dtype: float64
-
query()
方法已添加,允许您使用几乎与 Python 语法完全相同的自然查询语法选择DataFrame
的元素。例如,In [99]: n = 20 In [100]: df = pd.DataFrame(np.random.randint(n, size=(n, 3)), columns=['a', 'b', 'c']) In [101]: df.query('a < b < c') Out[101]: a b c 11 1 5 8 15 8 16 19
选择所有
df
中a < b < c
评估为True
的行。有关更多详细信息,请参阅文档。 -
pd.read_msgpack()
和pd.to_msgpack()
现在是序列化任意 pandas(和 python 对象)的支持方法,以轻量级便携二进制格式。请参阅文档警告
由于这是一个实验性库,存储格式可能在未来的发布中不稳定。
df = pd.DataFrame(np.random.rand(5, 2), columns=list('AB')) df.to_msgpack('foo.msg') pd.read_msgpack('foo.msg') s = pd.Series(np.random.rand(5), index=pd.date_range('20130101', periods=5)) pd.to_msgpack('foo.msg', df, s) pd.read_msgpack('foo.msg')
您可以传递
iterator=True
以迭代解压缩的结果for o in pd.read_msgpack('foo.msg', iterator=True): print(o)
-
pandas.io.gbq
提供了一种简单的方法,通过 pandas DataFrames 从 Google 的 BigQuery 数据集中提取数据,并加载数据。BigQuery 是一个高性能类似 SQL 的数据库服务,用于针对极大数据集执行临时查询。查看文档from pandas.io import gbq # A query to select the average monthly temperatures in the # in the year 2000 across the USA. The dataset, # publicata:samples.gsod, is available on all BigQuery accounts, # and is based on NOAA gsod data. query = """SELECT station_number as STATION, month as MONTH, AVG(mean_temp) as MEAN_TEMP FROM publicdata:samples.gsod WHERE YEAR = 2000 GROUP BY STATION, MONTH ORDER BY STATION, MONTH ASC""" # Fetch the result set for this query # Your Google BigQuery Project ID # To find this, see your dashboard: # https://console.developers.google.com/iam-admin/projects?authuser=0 projectid = 'xxxxxxxxx' df = gbq.read_gbq(query, project_id=projectid) # Use pandas to process and reshape the dataset df2 = df.pivot(index='STATION', columns='MONTH', values='MEAN_TEMP') df3 = pd.concat([df2.min(), df2.mean(), df2.max()], axis=1, keys=["Min Tem", "Mean Temp", "Max Temp"])
结果 DataFrame 是:
> df3 Min Tem Mean Temp Max Temp MONTH 1 -53.336667 39.827892 89.770968 2 -49.837500 43.685219 93.437932 3 -77.926087 48.708355 96.099998 4 -82.892858 55.070087 97.317240 5 -92.378261 61.428117 102.042856 6 -77.703334 65.858888 102.900000 7 -87.821428 68.169663 106.510714 8 -89.431999 68.614215 105.500000 9 -86.611112 63.436935 107.142856 10 -78.209677 56.880838 92.103333 11 -50.125000 48.861228 94.996428 12 -50.332258 42.286879 94.396774
警告
要使用此模块,您将需要一个 BigQuery 帐户。有关详细信息,请参阅<
cloud.google.com/products/big-query
>截至 2013 年 10 月 10 日,Google 的 API 中存在一个错误,阻止结果集超过 100,000 行。修补程序计划于 2013 年 10 月 14 日那周发布。
内部重构
在 0.13.0 中进行了主要重构,主要是将Series
从NDFrame
子类化,NDFrame
目前是DataFrame
和Panel
的基类,以统一方法和行为。Series
以前直接从ndarray
子类化。(GH 4080, GH 3862, GH 816)
警告
与< 0.13.0 存在两个潜在的不兼容性
-
使用某些 numpy 函数以前会在传递
Series
作为参数时返回Series
。这似乎只影响np.ones_like
、np.empty_like
、np.diff
和np.where
。现在这些函数返回ndarrays
。In [102]: s = pd.Series([1, 2, 3, 4])
Numpy 用法
In [103]: np.ones_like(s) Out[103]: array([1, 1, 1, 1]) In [104]: np.diff(s) Out[104]: array([1, 1, 1]) In [105]: np.where(s > 1, s, np.nan) Out[105]: array([nan, 2., 3., 4.])
Pandonic 用法
In [106]: pd.Series(1, index=s.index) Out[106]: 0 1 1 1 2 1 3 1 dtype: int64 In [107]: s.diff() Out[107]: 0 NaN 1 1.0 2 1.0 3 1.0 dtype: float64 In [108]: s.where(s > 1) Out[108]: 0 NaN 1 2.0 2 3.0 3 4.0 dtype: float64
-
直接将
Series
传递给期望ndarray
类型的 cython 函数将不再直接起作用,必须传递Series.values
,请参阅 Enhancing Performance -
Series(0.5)
以前会返回标量0.5
,现在会返回一个包含 1 个元素的Series
-
此更改破坏了
rpy2<=2.3.8
。已针对 rpy2 提出了一个问题,并在GH 5698中详细介绍了解决方法。感谢@JanSchulz。 -
保留了对 0.13 之前创建的 pickles 的 Pickle 兼容性。这些必须使用
pd.read_pickle
进行反序列化,请参阅 Pickling。 -
重构了 series.py/frame.py/panel.py,将通用代码移动到 generic.py。
-
添加了
_setup_axes
以创建通用的 NDFrame 结构 -
移动的方法
-
from_axes,_wrap_array,axes,ix,loc,iloc,shape,empty,swapaxes,transpose,pop
-
__iter__,keys,__contains__,__len__,__neg__,__invert__
-
convert_objects,as_blocks,as_matrix,values
-
__getstate__,__setstate__
(frame/panel 中保留了兼容性) -
__getattr__,__setattr__
-
_indexed_same,reindex_like,align,where,mask
-
fillna,replace
(Series
的 replace 现在与DataFrame
一致) -
filter
(还添加了轴参数以选择性地在不同轴上进行过滤) -
reindex,reindex_axis,take
-
truncate
(移动为NDFrame
的一部分)
-
-
-
这些是使
Panel
与DataFrame
更一致的 API 更改。-
在指定相同轴的
Panel
上执行swapaxes
现在会返回一个副本 -
支持属性访问进行设置
-
filter 支持与原始
DataFrame
filter 相同的 API
-
-
调用没有参数的 reindex 现在将返回输入对象的副本
-
TimeSeries
现在是Series
的别名。属性is_time_series
可用于区分(如果需要) -
重构稀疏对象以使用 BlockManager
-
在 internals 中创建了一个新的块类型,
SparseBlock
,可以容纳多种数据类型,不可合并。SparseSeries
和SparseDataFrame
现在从层次结构(Series/DataFrame)继承更多方法,并不再从SparseArray
继承(而是SparseBlock
的对象)。 -
稀疏套件现在支持与非稀疏数据的集成。非浮点稀疏数据是可支持的(部分实现)
-
在 DataFrame 中对稀疏结构进行操作应该保持稀疏性,合并类型操作将转换为稠密(然后再转换为稀疏),因此可能有些低效
-
为
SparseSeries
启用setitem
以支持布尔值/整数/切片 -
SparsePanels
的实现未更改(例如不使用 BlockManager,需要工作)
-
-
向 Series/DataFrame 添加了
ftypes
方法,类似于dtypes
,但指示底层是稀疏的/稠密的(以及 dtype) -
所有
NDFrame
对象现在都可以使用__finalize__()
来指定从现有对象传播到新对象的各种值(例如Series
中的name
现在将更自动地跟随) -
现在通过一系列生成的类进行内部类型检查,允许
isinstance(value, klass)
而无需直接导入 klass,感谢@jtratner -
修复了 Series 更新中的一个 bug,其中父框架未根据更改更新其缓存(GH 4080)或类型(GH 3217,fillna(GH 3386)
-
重构
Series.reindex
到 core/generic.py(GH 4604,GH 4618),允许在 Series 上重新索引时使用method=
-
Series.copy
不再接受order
参数,现在与NDFrame
的 copy 方法保持一致 -
将
rename
方法重构到 core/generic.py;修复了Series.rename
(GH 4605),并为Panel
添加了具有相同签名的rename
-
将
clip
方法重构到 core/generic.py(GH 4798) -
将
_get_numeric_data/_get_bool_data
重构到 core/generic.py,允许 Series/Panel 功能 -
Series
(用于索引)/Panel
(用于项目)现在允许对其元素进行属性访问(GH 1903)In [109]: s = pd.Series([1, 2, 3], index=list('abc')) In [110]: s.b Out[110]: 2 In [111]: s.a = 5 In [112]: s Out[112]: a 5 b 2 c 3 dtype: int64
Bug 修复
-
HDFStore
-
当使用不同的块排序附加时,引发无效的
TypeError
���不是ValueError
(GH 4096) -
read_hdf
没有遵守传递的mode
(GH 4504) -
现在可以正确地附加一个长度为 0 的表格了(GH 4273)
-
当同时传递
append
和table
参数时,to_hdf
会引发异常(GH 4584) -
从具有跨 dtype 重复列的存储中读取会引发异常(GH 4767)
-
修复了当列名不是字符串时未正确引发
ValueError
的 bug(GH 4956) -
以 Fixed 格式编写的零长度系列未正确反序列化。(GH 4708)。
-
修复了 pyt3 上的解码性能问题(GH 5441)。
-
在存储之前验证 MultiIndex 中的级别(GH 5527)。
-
正确处理具有 Panel 的
data_columns
(GH 5717)。
-
-
修复了
tslib.tz_convert(vals, tz1, tz2)
中的错误:尝试访问 trans[pos + 1]时可能会引发 IndexError 异常(GH 4496)。 -
修复了
PeriodIndex.map
中使用str
会返回索引的 str 表示形式的错误(GH 4136)。 -
在使用自定义 matplotlib 默认颜色时修复了
test_time_series_plot_color_with_empty_kwargs
的测试失败(GH 4345)。 -
修复了 stata IO 测试的运行问题。现在使用临时文件进行写入(GH 4353)。
-
修复了
DataFrame.sum
比整数值框架的DataFrame.mean
慢的问题(GH 4365)。 -
read_html
测试现在可以在 Python 2.6 中工作(GH 4351)。 -
修复了因未定义本地变量而引发
NameError
的network
测试错误(GH 4381)。 -
在
to_json
中,如果传递的orient
会因为重复索引而导致数据丢失,就会引发错误(GH 4359)。 -
在
to_json
中,修复日期处理,使毫秒成为默认时间戳,正如文档字符串所说的那样(GH 4362)。 -
修复了 JSON NaT 处理问题,现在 NaT 被序列化为
null
(GH 4498)。 -
修复了 JSON 对象键中可转义字符的 JSON 处理问题(GH 4593)。
-
在
na_values=None
时传递keep_default_na=False
时修复了错误(GH 4318)。 -
在 DataFrame 具有重复列和混合数据类型时,修复了
values
引发错误的问题,出现在(GH 4377)中。 -
在
read_json
中,当orient='split'
时,修复了重复列和类型转换导致的错误(GH 4377)。 -
修复了 JSON 中的 bug,其中具有除‘.’以外的小数分隔符的区��设置在编码/解码某些值时引发异常的问题(GH 4918)
-
修复了使用
PeriodIndex
进行.iat
索引的问题(GH 4390) -
修复了
PeriodIndex
与自身连接返回新实例而不是相同实例的问题(GH 4379); 还为其他索引类型添加了测试 -
修复了在使用 CSV cparser 和 usecols 参数时,所有 dtypes 都被转换为 object 的 bug(GH 3192)
-
修复了合并块时导致结果 DataFrame 部分设置 _ref_locs 的问题(GH 4403)
-
修复了使用顶层 matplotlib API 调用 hist 子图时被覆盖的问题(GH 4408)
-
修复了 py3 兼容性问题,其中 bytes 被 repr 为元组的问题(GH 4455)
-
修复了如果项目命名为'a'时 Panel 属性命名冲突的问题(GH 3440)
-
修复了绘图时重复索引引发异常的问题(GH 4486)
-
修复了 cumsum 和 cumprod 在 bool dtypes 上不起作用的问题(GH 4170, GH 4440)
-
修复了在
xs
中的 Panel 切片问题,返回了一个不正确的 dimmed 对象(GH 4016) -
修复了使用转置框架进行 Panel 赋值的问题(GH 3830)
-
在使用 Panel 和 Panel 作为需要对齐的值进行设置索引时引发异常(GH 3777)
-
修复了对具有多个 dtypes 的重复 MultiIndex 进行排序时的问题(GH 4516)
-
修复了
DataFrame.set_values
中的 bug,导致扩展索引时丢失 name 属性的问题(GH 3742, GH 4039) -
修复了在
MultiIndex
上可以设置单独的names
、levels
和labels
而不进行验证的问题(GH 3714,GH 4039)。 -
在
pivot_table
中修复了一个问题(GH 3334)。如果values
是索引,则边距未计算。 -
修复了在与日期时间操作时具有
np.timedelta64
或np.offsets.DateOffset
的 rhs 的 bug(GH 4532)。 -
修复了系列/日期时间索引和
np.timedelta64
之间的算术运算不一致的问题(GH 4134)以及 NumPy 1.6 中的错误时间间隔(GH 4135)。 -
修复了在 Windows 上使用 PY3 时
pd.read_clipboard
的 bug(GH 4561);未正确解码。 -
tslib.get_period_field()
和tslib.get_period_field_arr()
现在在 code 参数超出范围时会引发异常(GH 4519,GH 4520)。 -
修复了空系列上的布尔索引丢失索引名称的问题(GH 4235),
infer_dtype
现在可以处理空数组。 -
修复了使用多个轴重新索引时的问题;如果轴匹配未替换当前轴,可能导致潜在的频率推断问题(GH 3317)。
-
修复了
DataFrame.apply
不正确重新引发异常的问题(导致原始堆栈跟踪被截断)。 -
修复了使用
ix/loc
和非唯一选择器进行选择的问题(GH 4619)。 -
修复了在现有列中使用 iloc/loc 进行赋值涉及 dtype 更改的问题(GH 4312,GH 5702)在核心索引中使用
Block.setitem
。 -
修复了在 csv_import 中浮点数的千位操作符处理不正确的 bug(GH 4322)。
-
修复了
CacheableOffset
未被多个DateOffset
正确使用的问题;这导致DateOffset
无法被缓存(GH 4609)。 -
修复了在 DataFrame 左侧使用 DataFrame 进行布尔比较,右侧是列表/元组的问题(GH 4576)。
-
修复了在
Series/DataFrame
上使用None
进行 setitem 时的错误/类型转换问题(GH 4667)。 -
修复了基于传入的非默认编码解码的问题在
pd.read_stata
中(GH 4626)。 -
修复了使用普通
ndarray
的DataFrame.from_records
的问题(GH 4727)。 -
修复了
Index.rename
和MultiIndex.rename
等中的一些不一致性。(GH 4718, GH 4628) -
使用
iloc/loc
时出现横截面和重复索引的错误(GH 4726) -
使用
to_csv
时使用QUOTE_NONE
导致Exception
的错误。(GH 4328) -
当 Series 索引的右侧长度不正确时未引发错误的错误已修复(GH 2702)
-
使用部分字符串选择作为 MultIndex 的一部分进行 MultiIndexing 时出现的错误(GH 4758)
-
在具有非唯一索引的索引上重新索引现在将引发
ValueError
的问题已修复(GH 4746) -
修复了使用
loc/ix
设置具有多级索引轴和 NumPy 数组的单个索引器时出现的错误,相关问题(GH 3777) -
使用切片索引时
iloc
出现失败的错误(GH 4771) -
在
read_fwf
中没有 colspecs 或 width 时出现不正确的错误消息。(GH 4774) -
修复了在 Python 3 中使用
read_fwf
读取压缩文件时出现的错误。(GH 3963) -
修复了具有重复索引和 dtype 更改的赋值的问题(GH 4686)
-
修复了在 Python 3 中读取压缩文件时将其作为
bytes
而不是str
的错误。简化了 Python 3 中处理生成字节的文件的操作(GH 3963, GH 4785). -
修复了与不同版本的 matplotlib 中对数刻度条形图的 ticklocs/ticklabels 相关的问题(GH 4789)
-
抑制了由 repr()发出的内部调用关联的 DeprecationWarning(GH 4391)
-
修复了使用
.loc
时出现重复索引和重复选择器的问题(GH 4825) -
修复了
DataFrame.sort_index
中的问题,当按单个列排序并传递一个ascending
列表时,ascending
参数被解释为True
(GH 4839, GH 4846) -
修复了
Panel.tshift
不起作用的问题。为Panel.shift
添加了freq
支持。(GH 4853) -
修复了使用 Python 引擎(即 PythonParser)时
TextFileReader
中的问题,千位分隔符不是“,”。(GH 4596) -
在使用
where
时,使用重复索引时出现的getitem
错误已修复。(GH 4879) -
修复了类型推断代码将浮点列强制转换为日期时间的问题。(GH 4601)
-
修复了
_ensure_numeric
不检查复数的问题。(GH 4902) -
修复了
convert_objects
对> 2 维的错误。(GH 4937) -
修复了
FrozenNDArray
和FrozenList
的字符串方法。(GH 4929) -
修复了在索引扩展场景中设置无效或超出范围值时的错误。(GH 4940)
-
对空
Series
进行fillna
的测试。(GH 4346),感谢 @immerrr -
修复了
read_csv
中 Python 解析器的skiprows
选项。(GH 4382) -
修复了
cut
无法与未显式传递标签的np.inf
级别一起使用的错误。(GH 3415) -
修复了
DatetimeIndex.union
中重叠检查的错误。(GH 4564) -
修复了
csv_parser
中千位分隔符和日期解析器之间的冲突。(GH 4678) -
在
dtypes
不相同时修复了追加的问题(显示混合 float/np.datetime64 的错误)。(GH 4993) -
修复了
DateOffset
的repr
。不再在kwds
中显示重复条目。移除了未使用的偏移字段。(GH 4638) -
修复了在使用
usecols
时读取read_csv
时索引名称错误的问题。仅适用于 c 解析器。(GH 4201) -
Timestamp
对象现在可以出现在与Series
或DataFrame
对象进行比较操作的左侧。(GH 4982) -
修复了使用
iloc/loc
通过np.nan
进行索引时的 bug(GH 5016)。 -
修复了低内存 c 解析器在同一文件的不同块中创建不同类型的 bug。现在强制转换为数值类型或引发警告(GH 3866)。
-
修复了将
Series
重塑为其自身形状时引发TypeError
的 bug(GH 4554)以及其他重塑问题。 -
使用混合整数/字符串索引设置
ix/loc
时出现的 bug(GH 4544)。 -
确保系列-系列布尔比较是基于标签的(GH 4947)。
-
使用时间戳部分索引器进行多级索引时出现 bug(GH 4294)。
-
修复了构建全为 nan 的框架的 MultiIndex 测试/修复(GH 4078)。
-
修复了当表格中有逗号时,
read_html()
无法正确推断值的 bug(GH 5029)。 -
修复了当传递
index_col=0
时,read_html()
错误解析的 bug(GH 5066)。 -
修复了
read_html()
在错误推断标题类型的 bug(GH 5048)。 -
修复了
DatetimeIndex
与PeriodIndex
连接导致堆栈溢出的 bug(GH 3899)。 -
修复了
groupby
对象不允许绘图的 bug(GH 5102)。 -
修复了
groupby
对象无法自动补全列名的 bug(GH 5102)。 -
修复了
groupby.plot()
及其相关函数多次复制图形的 bug(GH 5102)。 -
在
fillna
时提供了object
类型的自动转换,相关(GH 5103)。 -
修复了默认选项在选项解析器清理中被覆盖的 bug(GH 5121)。
-
对于使用类似列表的
iloc
索引,将列表/ndarray 视为相同(GH 5006)。 -
修复了
MultiIndex.get_level_values()
中缺失值的 bug(GH 5074)。 -
修复了使用 datetime64 输入的 Timestamp()的边界检查(GH 4065)。
-
修复了
TestReadHtml
未调用正确的read_html()
函数的 bug(GH 5150)。 -
修复了
NDFrame.replace()
中的一个 bug,使替换看起来好像(错误地)使用了正则表达式(GH 5143)。 -
为 to_datetime 修复更好的错误消息(GH 4928)。
-
确保在 travis-ci 上测试不同的区域设置(GH 4918)。还添加了一些用于获取区域设置和使用上下文管理器设置区域设置的实用程序。
-
构造函数中的复合 dtypes 引发
NotImplementedError
(GH 5191)。 -
比较重复框架中的 bug(GH 4421)相关。
-
在重复框架上的描述中存在 bug。
-
to_datetime
中带有格式和coerce=True
的 bug 未引发异常(GH 5195)。 -
在使用多个索引器和需要广播的 Series 的 rhs 的
loc
设置中存在 bug(GH 5206)。 -
修复了在
MultiIndex
上设置级别或标签时不会清除缓存的values
属性,因此返回错误的values
的 bug([GH 5215](https://github.com/pandas-dev/pandas/issues/5215))。 -
修复了对分组的 DataFrame 或 Series 进行过滤时未保持原始顺序的 bug(GH 4621)。
-
修复了具有业务日期频率的
Period
始终向前滚动的 bug,如果在非工作日(GH 5203)。 -
修复了 Excel 写入器中具有重复列名的框架未正确写入的 bug(GH 5235)。
-
修复了在 Series 上具有非唯一索引时的
drop
问题(GH 5248)。 -
由于在文件中传递的名称多于列数而导致的 C 解析器中的段错误已修复(GH 5156)。
-
修复了
Series.isin
与日期/时间类型的 dtypes 一起使用的 bug(GH 5021)。 -
C 和 Python 解析器现在可以处理更常见的 MultiIndex 列格式,该格式没有索引名称的行。(GH 4702)
-
尝试将超出范围的日期用作对象 dtype 时出现 bug。(GH 5312)
-
尝试显示嵌入的 PandasObject 时出现 bug。(GH 5324)
-
允许操作时间戳以返回日期时间,如果结果超出范围则相关(GH 5312)
-
修复了
initObjToJSON()
的返回值/类型签名,以使其与 numpy 的import_array()
兼容。(GH 5334, GH 5326) -
在 DataFrame 上重命名然后设置索引时出现 bug。(GH 5344)
-
测试套件在测试图形时不再保留临时文件。(GH 5347)(感谢 @yarikoptic 发现这个问题!)
-
修复了 win32 上的 html 测试。(GH 4580)
-
确保
head/tail
是基于iloc
的。(GH 5370) -
修复了
PeriodIndex
字符串表示中存在 1 或 2 个元素时的 bug。(GH 5372) -
GroupBy 方法
transform
和filter
可用于具有重复(非唯一)索引的 Series 和 DataFrames。(GH 4620) -
修复了空系列在 repr 中不打印名称的问题。(GH 4651)
-
确保测试默认在临时目录中创建临时文件。(GH 5419)
-
标量的
pd.to_timedelta
返回一个标量。(GH 5410) -
pd.to_timedelta
接受NaN
和NaT
,返回NaT
而不是引发异常。(GH 5437) -
在更大尺寸的 pandas 对象上
isnull
的性能改进 -
修复了各种 setitem 与 1d ndarray 不具有与索引器匹配长度的 bug。(GH 5508)
-
在 MultiIndex 和
iloc
中使用 getitem 时出现 bug。(GH 5528) -
在 Series 上进行 delitem 时出现 bug。(GH 5542)
-
在使用自定义函数并且对象未被改变时,apply 中的 bug 修复。(GH 5545)
-
在使用
loc
从非唯一索引中选择时出现 bug。(GH 5553) -
在用户函数返回
None
时,groupby 返回非一致类型的 bug。(GH 5592) -
解决 numpy 1.7.0 中的回归问题,该问题错误地从
ndarray.item
引发 IndexError(GH 5666) -
在具有非唯一索引的对象的重复索引中的错误(GH 5678)
-
在使用 Series 和传递的 series/dict 时 fillna 中的错误(GH 5703)
-
在具有类似日期时间的分组器的 groupby transform 中的错误(GH 5712)
-
在 PY3 中使用某些键时 MultiIndex 选择中的错误(GH 5725)
-
在某些情况下,不同 dtype 的行连接失败(GH 5754)
贡献者
总共有 77 人为这个版本贡献了补丁。名字后面带有“+”的人第一次贡献了补丁。
-
Agustín Herranz +
-
Alex Gaudio +
-
Alex Rothberg +
-
Andreas Klostermann +
-
Andreas Würl +
-
Andy Hayden
-
Ben Alex +
-
Benedikt Sauer +
-
Brad Buran
-
Caleb Epstein +
-
Chang She
-
Christopher Whelan
-
DSM +
-
Dale Jung +
-
Dan Birken
-
David Rasch +
-
Dieter Vandenbussche
-
Gabi Davar +
-
Garrett Drapala
-
Goyo +
-
Greg Reda +
-
Ivan Smirnov +
-
Jack Kelly +
-
Jacob Schaer +
-
Jan Schulz +
-
Jeff Tratner
-
Jeffrey Tratner
-
John McNamara +
-
John W. O’Brien +
-
Joris Van den Bossche
-
Justin Bozonier +
-
Kelsey Jordahl
-
Kevin Stone
-
Kieran O’Mahony
-
Kyle Hausmann +
-
Kyle Kelley +
-
Kyle Meyer
-
Mike Kelly
-
Mortada Mehyar +
-
Nick Foti +
-
Olivier Harris +
-
Ondřej Čertík +
-
PKEuS
-
Phillip Cloud
-
Pierre Haessig +
-
Richard T. Guy +
-
Roman Pekar +
-
Roy Hyunjin Han
-
Skipper Seabold
-
Sten +
-
Thomas A Caswell +
-
Thomas Kluyver
-
Tiago Requeijo +
-
TomAugspurger
-
Trent Hauck
-
Valentin Haenel +
-
Viktor Kerkez +
-
Vincent Arel-Bundock
-
Wes McKinney
-
Wes Turner +
-
Weston Renoud +
-
Yaroslav Halchenko
-
Zach Dwiel +
-
chapman siu +
-
chappers +
-
d10genes +
-
danielballan
-
daydreamt +
-
engstrom +
-
jreback
-
monicaBee +
-
prossahl +
-
rockg +
-
unutbu +
-
westurner +
-
y-p
-
zach powers
版本 0.12.0(2013 年 7 月 24 日)
这是从 0.11.0 开始的一个重大发布,包括几个新功能和增强功能,以及大量的错误修复。
重点包括一致的 I/O API 命名方案,用于读取 html、将 MultiIndexes 写入 csv 文件、读取和写入 STATA 数据文件、读取和写入 JSON 格式文件的例程,Python 3 对 HDFStore
的支持,通过 filter
进行 groupby 表达式的过滤,以及接受正则表达式的经过改进的 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、DataFrame 上的取模和整数除法,使其表现类似于
float
dtypes,根据需要返回np.nan
或np.inf
(GH 3590)。这修正了一个 numpy 的 bug,即将integer
和float
dtypes 视为不同。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
向
groupby
添加squeeze
关键字,以允许从 DataFrame -> Series 的缩减,如果组是唯一的话。这是从 0.10.1 开始的一个回归。我们正在恢复到之前的行为。这意味着 groupby 将返回相同形状的对象,无论组是否唯一。回滚此问题(GH 2893)与(GH 3596)。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
,例如,布尔 Series,即使具有整数标签,也会引发。由于iloc
是纯粹基于位置的,因此 Series 上的标签是不可对齐的(GH 3631)这种情况很少见,有很多替代方案。这保留了
iloc
API 的纯基于位置的特性。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]
将引发ValueError
绘图函数的
raise_on_error
参数已移除。相反,当对象的dtype
是object
时,绘图函数会引发TypeError
,以提醒您尽量避免使用object
数组,因此如果需要绘制某些内容,则应将其转换为适当的数值 dtype。向 DataFrame 绘图方法添加
colormap
关键字。接受 matplotlib colormap 对象(例如,matplotlib.cm.jet)或此类对象的字符串名称(例如,'jet')。对于每列,将从 colormap 中进行采样以选择颜色。请参阅 Colormaps 以获取更多信息。(GH 3860)
DataFrame.interpolate()
现在已被弃用。请改用DataFrame.fillna()
和DataFrame.replace()
(GH 3582,GH 3675,GH 3676)
DataFrame.replace()
的method
和axis
参数已弃用
DataFrame.replace
的infer_types
参数已删除,并且现在默认执行转换(GH 3907)在
DataFrame.insert
中添加了关键字allow_duplicates
,如果为True
,则允许插入重复列,默认为False
(与 0.12 之前相同)(GH 3679)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_html
和DataFrame.to_latex
现在接受路径作为它们的第一个参数(GH 3702)不允许在
datetime64[ns]
上进行 astypes,除了转换为object
,以及在timedelta64[ns]
上进行 astypes,转换为object/int
(GH 3425)对于某些所谓的缩减操作,
datetime64
类型的行为发生了变化(GH 3726)。现在,在Series
上执行以下操作会引发TypeError
,在DataFrame
上执行这些操作会返回一个空Series
,类似于在例如slice
对象的DataFrame
上执行这些操作:
- sum、prod、mean、std、var、skew、kurt、corr 和 cov
read_html
在读取时现在默认为None
,当 lxml 无法解析时,将回退到bs4
+html5lib
。也可以尝试一系列解析器直到成功内部
pandas
类层次结构已发生变化(轻微)。以前的PandasObject
现在称为PandasContainer
,而新的PandasObject
已成为PandasContainer
以及Index
、Categorical
、GroupBy
、SparseList
和SparseArray
(及其基类)的基类。目前,PandasObject
提供字符串方法(来自StringMixin
)(GH 4090,GH 4092)新的
StringMixin
,给定一个__unicode__
方法,获得 Python 2 和 Python 3 兼容的字符串方法(__str__
、__bytes__
和__repr__
)。加上字符串安全性。现在在 pandas 库的许多地方使用。(GH 4090,GH 4092)
IO 增强
pd.read_html()
现在可以解析 HTML 字符串、文件或 URL 并返回 DataFrame,由 @cpcloud 提供。 (GH 3477, GH 3605, GH 3606, GH 3616)。它与一个 单一 解析器后端配合使用:BeautifulSoup4 + html5lib 查看文档您可以使用
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()
不再对日期字符串进行强制转换(GH 3656)。警告
您可能需要安装旧版本的 BeautifulSoup4,查看安装文档
添加了用于读取和写入 Stata 文件的模块:
pandas.io.stata
(GH 1512)通过read_stata
顶级函数进行读取,通过to_stata
DataFrame 方法进行写入,查看文档添加了用于读取和写入 json 格式文件的模块:
pandas.io.json
通过read_json
顶级函数进行读取,并通过to_json
DataFrame 方法进行写入,查看文档 各种问题 (GH 1226, GH 3804, GH 3876, GH 3867, GH 1305)读取和写入 csv 格式文件的
MultiIndex
列支持
read_csv
中的header
选项现在接受要从中读取索引的行列表。现在可以在
to_csv
和read_csv
中指定选项tupleize_cols
,以提供对通过元组列表写入和读取MultIndex
列的 0.12 版行为的兼容性。在 0.12 中的默认行为是写入元组列表并 不 将元组列表解释为MultiIndex
列。注意:0.12 版的默认行为与以前的版本保持不变,但从 0.13 开始,默认的 写入 和 读取
MultiIndex
列的格式将是新的格式。 (GH 3571, GH 1651, GH 3141)如果未指定
index_col
(例如,您没有索引,或者使用df.to_csv(..., index=False
写入了索引),则列索引上的任何names
将丢失。In [16]: mi_idx = pd.MultiIndex.from_arrays([[1, 2, 3, 4], list("abcd")], names=list("ab")) In [17]: mi_col = pd.MultiIndex.from_arrays([[1, 2], list("ab")], names=list("cd")) In [18]: df = pd.DataFrame(np.ones((4, 2)), index=mi_idx, columns=mi_col) In [19]: df.to_csv("mi.csv") In [20]: print(open("mi.csv").read()) c,,1,2 d,,a,b a,b,, 1,a,1.0,1.0 2,b,1.0,1.0 3,c,1.0,1.0 4,d,1.0,1.0 In [21]: pd.read_csv("mi.csv", header=[0, 1, 2, 3], index_col=[0, 1]) Out[21]: c 1 2 d a b a Unnamed: 2_level_2 Unnamed: 3_level_2 1 1.0 1.0 2 b 1.0 1.0 3 c 1.0 1.0 4 d 1.0 1.0
对 Python3 的
HDFStore
(通过PyTables 3.0.0
)的支持通过
read_hdf
支持迭代器,当迭代完成时自动打开和关闭存储。这仅适用于 tablesIn [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()
现在允许在包含对象 dtype 的Series
上使用正则表达式。请参阅常规文档中的示例部分通过字符串表达式替换例如,你可以这样做
In [22]: df = pd.DataFrame({"a": list("ab.."), "b": [1, 2, 3, 4]}) In [23]: df.replace(regex=r"\s*\.\s*", value=np.nan) Out[23]: a b 0 a 1 1 b 2 2 NaN 3 3 NaN 4
将字符串
'.'
的所有出现替换为零个或多个周围空格的实例为NaN
。常规字符串替换仍然按预期工作。例如,你可以这样做
In [24]: df.replace(".", np.nan) Out[24]: a b 0 a 1 1 b 2 2 NaN 3 3 NaN 4
将字符串
'.'
的所有出现替换为NaN
。
pd.melt()
现在接受可选参数var_name
和value_name
,以指定返回的 DataFrame 的自定义列名。
pd.set_option()
现在允许 N 个选项,值对(GH 3667)。假设我们有一个选项
'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 [25]: sf = pd.Series([1, 1, 2, 3, 3, 3]) In [26]: sf.groupby(sf).filter(lambda x: x.sum() > 2) Out[26]: 3 3 4 3 5 3 dtype: int64
filter
的参数必须是一个函数,应用于整个组,返回True
或False
。另一个有用的操作是过滤出只属于只有几个成员的组的元素。
In [27]: dff = pd.DataFrame({"A": np.arange(8), "B": list("aabbbbcc")}) In [28]: dff.groupby("B").filter(lambda x: len(x) > 2) Out[28]: A B 2 2 b 3 3 b 4 4 b 5 5 b
或者,而不是丢弃有问题的组,我们可以返回一个类似索引的对象,其中未通过过滤器的组填充为 NaN。
In [29]: dff.groupby("B").filter(lambda x: len(x) > 2, dropna=False) Out[29]: 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
参数(GH 3834)在连接操作期间,DatetimeIndexes 不再尝试转换混合整数索引(GH 3877)
Timestamp.min 和 Timestamp.max 现在表示有效的 Timestamp 实例,而不是默认的 datetime.min 和 datetime.max(分别),感谢@SleepingPills
当未找到表格且检测到 BeautifulSoup==4.2.0 时,
read_html
现在会引发异常(GH 4214)
实验性功能
添加了实验性的
CustomBusinessDay
类,以支持具有自定义假日日历和自定义周掩码的DateOffsets
。(GH 2301)注意
这使用了 Numpy 1.7 中引入的
numpy.busdaycalendar
API,因此需要 Numpy 1.7.0 或更新版本。In [30]: from pandas.tseries.offsets import CustomBusinessDay In [31]: from datetime import datetime # As an interesting example, let's look at Egypt where # a Friday-Saturday weekend is observed. In [32]: weekmask_egypt = "Sun Mon Tue Wed Thu" # They also observe International Workers' Day so let's # add that for a couple of years In [33]: holidays = ["2012-05-01", datetime(2013, 5, 1), np.datetime64("2014-05-01")] In [34]: bday_egypt = CustomBusinessDay(holidays=holidays, weekmask=weekmask_egypt) In [35]: dt = datetime(2013, 4, 30) In [36]: print(dt + 2 * bday_egypt) 2013-05-05 00:00:00 In [37]: dts = pd.date_range(dt, periods=5, freq=bday_egypt) In [38]: 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
Bug 修复
绘图函数现在在尝试绘制任何内容之前会引发
TypeError
,如果相关对象的dtype
为object
(GH 1818,GH 3572,GH 3911,GH 3912),但如果可能的话,它们将尝试将对象数组转换为数值数组,以便您仍然可以绘制,例如,具有浮点数的对象数组。这发生在任何绘图发生之前,消除了任何不必要的绘图显示。如果
value
参数是列表或元组,则fillna
方法现在��引发TypeError
。
Series.str
现在支持迭代(GH 3638)。您可以迭代Series
中每个字符串的各个元素。每次迭代都会产生一个Series
,原始Series
的每个索引处要么是单个字符,要么是NaN
。例如,In [38]: strs = "go", "bow", "joe", "slow" In [32]: ds = pd.Series(strs) In [33]: 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
,其中包含Series
中最长字符串的最后一个元素,所有其他元素均为NaN
。在这里,由于'slow'
是最长的字符串,且没有其他长度相同的字符串,因此在生成的Series
中,'w'
是唯一的非空字符串。
HDFStore
非唯一索引支持已澄清(GH 3468)。
- 修复将新索引分配给 DataFrame 中的重复索引将失败(GH 3468)
- 修复具有重复索引的 DataFrame 的构建
ref_locs
支持允许跨数据类型重复索引,允许iget
支持始终找到索引(即使跨数据类型)(GH 2194)- 在具有非唯一索引的 DataFrame 上应用
applymap
现在可以正常工作(已删除警告)(GH 2786),并修复(GH 3230)- 修复
to_csv
以处理非唯一列(GH 3495)- 具有
getitem
的重复索引将按正确顺序返回项目(GH 3455,GH 3457),并处理缺失元素,如唯一索引(GH 3561)- 具有重复索引且空 DataFrame.from_records 将返回正确的框架 (GH 3562)
- 修复了当跨数据类型存在重复时,Concat 产生非唯一列的问题 (GH 3602)
- 允许对非唯一列进行插入/删除 (GH 3679)
- 通过
loc
和相关方法修复了使用切片的非唯一索引 (GH 3659)- 允许对非唯一列进行插入/删除 (GH 3679)
- 扩展
reindex
以正确处理非唯一索引 (GH 3679)DataFrame.itertuples()
现在可以处理具有重复列名的框架 (GH 3873)- 通过
iloc
进行非唯一索引的错误 (GH 4017); 为基于位置的获取添加了takeable
参数- 通过
.ix/.loc
和__getitem__
允许在系列中进行非唯一索引 (GH 4246)- 通过
.ix/.loc
修复了非唯一索引内存分配问题 (GH 4280)
DataFrame.from_records
不接受空的记录数组 (GH 3682)
read_html
现在正确跳过测试 (GH 3741)修复了在
DataFrame.replace
中to_replace
参数中使用编译的正则表达式时无效的 bug (GH 3907)改进了
network
测试装饰器以捕获IOError
(因此也捕获了URLError
)。 添加了with_connectivity_check
装饰器,以允许显式检查网站作为查看网络连接性的代理。 另外,为装饰器添加了新的optional_args
工厂。 (GH 3910, GH 3914)修复了测试问题,其中打开了太多的套接字,导致连接重置问题 (GH 3982, GH 3985, GH 4028, GH 4054)
修复了 test_yahoo、test_google 中失败的测试,其中未检索到符号但正在被访问 (GH 3982, GH 3985, GH 4028, GH 4054)
如果未传递当前环境的图形,则
Series.hist
现在将获取图形修复了 1xN DataFrame 在 1xN 掩码上出错的错误(GH 4071)
修复了在 python3 下运行
tox
时 pickle 导入被不兼容地重写的 bug(GH 4062, GH 4063)修复了 sharex 和 sharey 未传递给 grouped_hist 的 bug(GH 4089)
修复了
DataFrame.replace
中当 regex=False 时未迭代嵌套字典的 bug(GH 4115)修复了在
to_datetime
中使用format
参数时微秒解析错误的 bug(GH 4152)修复了
PandasAutoDateLocator
中invert_xaxis
错误触发MilliSecondLocator
的 bug(GH 3990)修复了绘图中对于 matplotlib 1.1.1 无效颜色映射未引发异常的 bug(GH 4215)
修复了在
DataFrame.plot(kind='kde')
中显示图例的 bug(GH 4216)修复了索引切片未携带名称属性的错误(GH 4226)
修复了在特定时区使用字符串数组初始化
DatetimeIndex
时的错误(GH 4229)修复了 html5lib 未正确跳过的 bug(GH 4265)
修复了
get_data_famafrench
未使用正确文件边缘的错误(GH 4281)
查看完整发布说明或 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
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
dtypes 以返回适当的np.nan
或np.inf
(GH 3590)。这纠正了一个 numpy 处理integer
和float
dtypes 不同的 bug。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
向
groupby
添加squeeze
关键字,以允许从 DataFrame -> Series 的减少,如果组是唯一的。这是从 0.10.1 开始的一个回归。我们正在恢复到以前的行为。这意味着 groupby 将返回相同形状的对象,无论组是否唯一。通过(GH 3596)撤销此问题(GH 2893)。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
当使用基于标签的索引器掩码进行布尔索引时,例如布尔 Series,即使具有整数标签,也会在
iloc
上引发。由于iloc
是纯粹基于位置的,Series 上的标签是不可对齐的(GH 3631)这种情况很少见,而且有很多替代方案。这样做保留了
iloc
API 的纯粹基于位置的特性。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]
会引发ValueError
绘图函数的
raise_on_error
参数已移除。相反,当对象的dtype
为object
时,绘图函数会引发TypeError
,以提醒您尽量避免object
数组,如果需要绘制某些内容,则应将其转换为适当的数值 dtype。向 DataFrame 绘图方法添加
colormap
关键字。接受 matplotlib colormap 对象(例如,matplotlib.cm.jet)或此类对象的字符串名称(例如,‘jet’)。对 colormap 进行采样以为每列选择颜色。请参阅 Colormaps 了解更多信息。(GH 3860)
DataFrame.interpolate()
现在已弃用。请改用DataFrame.fillna()
和DataFrame.replace()
(GH 3582, GH 3675, GH 3676)
DataFrame.replace()
的method
和axis
参数已废弃
DataFrame.replace
的infer_types
参数已移除,默认现在会执行转换(GH 3907)向
DataFrame.insert
添加关键字allow_duplicates
,如果为True
,则允许插入重复列,默认为False
(与 0.12 之前的行为相同)(GH 3679)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_html
和DataFrame.to_latex
现在接受路径作为它们的第一个参数 (GH 3702)不允许对
datetime64[ns]
执行除了到object
的 astypes 外的操作,也不允许对timedelta64[ns]
执行到object/int
的操作 (GH 3425)关于某些所谓的减少操作,
datetime64
dtypes 的行为已更改 (GH 3726). 当在Series
上执行以下操作时,现在会引发TypeError
,并在DataFrame
上执行时返回一个空Series
,类似于在slice
对象的DataFrame
上执行这些操作:
- sum、prod、mean、std、var、skew、kurt、corr 和 cov
read_html
现在在读取时默认为None
,当 lxml 解析失败时回退到bs4
+html5lib
。也可以尝试一系列解析器直到成功为止内部的
pandas
类层次结构已经改变(略)。以前的PandasObject
现在被称为PandasContainer
,而新的PandasObject
已成为PandasContainer
以及Index
、Categorical
、GroupBy
、SparseList
和SparseArray
(+它们的基类)的基类。当前,PandasObject
提供了字符串方法(来自StringMixin
)。 (GH 4090, GH 4092)新的
StringMixin
,给定一个__unicode__
方法,获取兼容 Python 2 和 Python 3 的字符串方法 (__str__
,__bytes__
, 和__repr__
)。加上整个 pandas 库中的字符串安全。现在在 pandas 库的许多地方都使用了它。 (GH 4090, GH 4092)
IO 增强
pd.read_html()
现在可以解析 HTML 字符串、文件或网址,并返回 DataFrames,感谢 @cpcloud。 (GH 3477, GH 3605, GH 3606, GH 3616). 它只与一个单一解析器后端兼容:BeautifulSoup4 + html5lib 查看文档你可以使用
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
是一个 Pythonlist
,所以pd.read_html()
和DataFrame.to_html()
不是逆操作。
pd.read_html()
不再对日期字符串执行强制转换 (GH 3656).警告
你可能需要安装一个较旧版本的 BeautifulSoup4,查看安装文档
添加了用于读写 Stata 文件的模块:
pandas.io.stata
(GH 1512),可通过read_stata
顶级函数进行读取,通过to_stata
DataFrame 方法进行写入,查看文档添加了用于读写 json 格式文件的模块:
pandas.io.json
,可通过read_json
顶级函数进行读取,通过to_json
DataFrame 方法进行写入,查看文档各种问题(GH 1226,GH 3804,GH 3876,GH 3867,GH 1305)支持读写 csv 格式文件的
MultiIndex
列
read_csv
中的header
选项现在接受要读取索引的行列表现在可以在
to_csv
和read_csv
中指定tupleize_cols
选项,以提供对通过元组列表写入和读取MultIndex
列的 0.12 之前行为的兼容性。0.12 中的默认行为是写入元组列表,不将元组列表解释为MultiIndex
列。注意:0.12 版本中的默认行为与之前的版本保持不变,但从 0.13 开始,默认写入和读取
MultiIndex
列的格式将采用新格式。(GH 3571,GH 1651,GH 3141)如果未指定
index_col
(例如,您没有索引,或者使用df.to_csv(..., index=False
写入),则列索引上的任何names
将丢失In [16]: mi_idx = pd.MultiIndex.from_arrays([[1, 2, 3, 4], list("abcd")], names=list("ab")) In [17]: mi_col = pd.MultiIndex.from_arrays([[1, 2], list("ab")], names=list("cd")) In [18]: df = pd.DataFrame(np.ones((4, 2)), index=mi_idx, columns=mi_col) In [19]: df.to_csv("mi.csv") In [20]: print(open("mi.csv").read()) c,,1,2 d,,a,b a,b,, 1,a,1.0,1.0 2,b,1.0,1.0 3,c,1.0,1.0 4,d,1.0,1.0 In [21]: pd.read_csv("mi.csv", header=[0, 1, 2, 3], index_col=[0, 1]) Out[21]: c 1 2 d a b a Unnamed: 2_level_2 Unnamed: 3_level_2 1 1.0 1.0 2 b 1.0 1.0 3 c 1.0 1.0 4 d 1.0 1.0
支持在 Python3 上通过
PyTables 3.0.0
实现对HDFStore
的支持通过
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()
现在允许在包含对象 dtype 的Series
上使用正则表达式。请参阅常规文档中的示例部分通过字符串表达式替换例如,您可以执行
In [22]: df = pd.DataFrame({"a": list("ab.."), "b": [1, 2, 3, 4]}) In [23]: df.replace(regex=r"\s*\.\s*", value=np.nan) Out[23]: a b 0 a 1 1 b 2 2 NaN 3 3 NaN 4
将所有字符串
'.'
替换为零个或多个周围空格的实例为NaN
常规字符串替换仍然按预期工作。例如,您可以执行
In [24]: df.replace(".", np.nan) Out[24]: a b 0 a 1 1 b 2 2 NaN 3 3 NaN 4
将所有字符串
'.'
替换为NaN
pd.melt()
现在接受可选参数var_name
和value_name
,以指定返回的 DataFrame 的自定义列名
pd.set_option()
现在允许 N 个选项,值对(GH 3667)假设我们有一个选项
'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 [25]: sf = pd.Series([1, 1, 2, 3, 3, 3]) In [26]: sf.groupby(sf).filter(lambda x: x.sum() > 2) Out[26]: 3 3 4 3 5 3 dtype: int64
filter
的参数必须是一个函数,该函数作用于整个组,返回True
或False
。另一个有用的操作是过滤掉属于仅有几个成员的组的元素。
In [27]: dff = pd.DataFrame({"A": np.arange(8), "B": list("aabbbbcc")}) In [28]: dff.groupby("B").filter(lambda x: len(x) > 2) Out[28]: A B 2 2 b 3 3 b 4 4 b 5 5 b
或者,我们可以返回一个类似索引的对象,其中未通过过滤器的组填充为 NaN。
In [29]: dff.groupby("B").filter(lambda x: len(x) > 2, dropna=False) Out[29]: 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
系列和数据框的
hist
方法现在接受一个figsize
参数(GH 3834)在连接操作期间,DatetimeIndexes 不再尝试转换混合整数索引(GH 3877)
Timestamp.min
和Timestamp.max
现在代表有效的Timestamp
实例,而不是默认的datetime.min
和datetime.max
(分别),感谢 @SleepingPills当未找到任何表格且检测到 BeautifulSoup==4.2.0 时,
read_html
现在会引发异常(GH 4214)
实验性功能
添加了实验性的
CustomBusinessDay
类,支持具有自定义假日日历和自定义周掩码的DateOffsets
。(GH 2301)注意
这使用了在 Numpy 1.7 中引入的
numpy.busdaycalendar
API,因此需要 Numpy 1.7.0 或更新版本。In [30]: from pandas.tseries.offsets import CustomBusinessDay In [31]: from datetime import datetime # As an interesting example, let's look at Egypt where # a Friday-Saturday weekend is observed. In [32]: weekmask_egypt = "Sun Mon Tue Wed Thu" # They also observe International Workers' Day so let's # add that for a couple of years In [33]: holidays = ["2012-05-01", datetime(2013, 5, 1), np.datetime64("2014-05-01")] In [34]: bday_egypt = CustomBusinessDay(holidays=holidays, weekmask=weekmask_egypt) In [35]: dt = datetime(2013, 4, 30) In [36]: print(dt + 2 * bday_egypt) 2013-05-05 00:00:00 In [37]: dts = pd.date_range(dt, periods=5, freq=bday_egypt) In [38]: 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
错误修复
如果关联对象的 dtype 为
object
,则绘图函数现在会在尝试绘制任何内容之前引发TypeError
(GH 1818, GH 3572, GH 3911, GH 3912),但如果可能的话,它们会尝试将对象数组转换为数字数组,以便您仍然可以绘制,例如,具有浮点数的对象数组。这在任何绘图发生之前发生,从而消除了任何错误绘图的可能性。如果
value
参数是列表或元组,则fillna
方法现在会引发TypeError
。
Series.str
现在支持迭代(GH 3638)。您可以迭代Series
中每个字符串的各个元素。每次迭代都会产生一个Series
,原始Series
中每个索引处要么是单个字符,要么是NaN
。例如,In [38]: strs = "go", "bow", "joe", "slow" In [32]: ds = pd.Series(strs) In [33]: 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
澄清非唯一索引支持(GH 3468)。
- 修复将新索引分配给 DataFrame 中的重复索引会失败的问题(GH 3468)。
- 修复使用重复索引构建 DataFrame 的问题。
- ref_locs 支持允许在不同数据类型之间具有重复索引,允许 iget 支持始终找到索引(即使在不同数据类型之间)(GH 2194)。
- 在具有非唯一索引的 DataFrame 上应用 applymap 现在可以正常工作(已删除警告)(GH 2786),并修复(GH 3230)。
- 修复 to_csv 处理非唯一列的问题(GH 3495)。
- 具有 getitem 的重复索引将按正确顺序返回项目(GH 3455,GH 3457),并处理缺失元素,如唯一索引(GH 3561)。
- 具有重复索引的空 DataFrame.from_records 将返回一个正确的框架(GH 3562)。
- 修复当重复跨数据类型时产生非唯一列的 Concat 问题(GH 3602)。
- 允许对非唯一列进行插入/删除操作(GH 3679)。
- 通过
loc
和相关方法修复使用切片进行非唯一索引的问题(GH 3659)。- 允许对非唯一列进行插入/删除操作(GH 3679)。
- 扩展
reindex
以正确处理非唯一索引(GH 3679)。DataFrame.itertuples()
现在可以处理具有重复列名的框架(GH 3873)。- 通过
iloc
进行非唯一索引的 bug 修复([GH 4017](https://github.com/pandas-dev/pandas/issues/4017);为reindex
添加了takeable
参数以进行基于位置的取值。- 通过
.ix/.loc
和__getitem__
在系列中允许非唯一索引(GH 4246)。- 修复使用
.ix/.loc
进行非唯一索引的内存分配问题(GH 4280)。
DataFrame.from_records
不接受空 recarrays(GH 3682)。
read_html
现在正确跳过测试了 (GH 3741)修复了使用
DataFrame.replace
中编译的正则表达式在to_replace
参数中不起作用的 bug (GH 3907)改进了
network
测试修饰符以捕获IOError
(因此也是URLError
)。添加了with_connectivity_check
修饰符,允许显式检查网站作为检查网络连接性的代理。此外,为修饰符添加了新的optional_args
修饰符工厂 (GH 3910, GH 3914)修复了测试问题,其中打开了太多的套接字,导致连接重置问题 (GH 3982, GH 3985, GH 4028, GH 4054)
修复了 test_yahoo、test_google 中的测试失败问题,其中未检索到符号但正在访问 (GH 3982, GH 3985, GH 4028, GH 4054)
Series.hist
现在会在当前环境中获取图形(如果未传递)修复了 1xN DataFrame 在 1xN 掩码上报错的 bug (GH 4071)
修复了在 python3 下运行
tox
时,pickle 导入以不兼容的方式重写的 bug (GH 4062, GH 4063)修复了未传递 sharex 和 sharey 到 grouped_hist 中的 bug (GH 4089)
修复了
DataFrame.replace
中的 bug,其中嵌套字典在 regex=False 时未被迭代 (GH 4115)修复了在使用
to_datetime
中的format
参数时微秒解析的 bug (GH 4152)修复了
PandasAutoDateLocator
中的 bug,其中invert_xaxis
错误地触发了MilliSecondLocator
(GH 3990)修复了绘图中无效色图未触发异常的 bug (GH 4215)
修复了在
DataFrame.plot(kind='kde')
中显示图例的问题 (GH 4216)修复了索引切片没有携带 name 属性的 bug (GH 4226)
修复了在特定时区中使用字符串数组初始化
DatetimeIndex
中的 bug (GH 4229)修复了 html5lib 没有被正确跳过的 bug(GH 4265)
修复了 get_data_famafrench 没有使用正确文件边缘的 bug(GH 4281)
查看完整的发行说明或 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
版本 0.11.0(2013 年 4 月 22 日)
这是从 0.10.1 版本开始的一个重要发布,其中包括许多新功能和增强功能,以及大量的错误修复。选择数据的方法已经增加了很多内容,Dtype 支持现在已经成熟。还有一些重要的 API 更改,长期使用 pandas 的用户应该密切关注。
文档中有一个新的部分,10 分钟入门 Pandas,主要面向新用户。
文档中有一个新的部分,食谱,其中包含 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 开始,这些方法可能会在未来版本中被弃用。
-
irow
-
icol
-
iget_value
请参阅按位置选择一节以获取替代方案。
Dtypes
数值数据类型将传播并可以共存于 DataFrame 中。如果传递了数据类型(可以直接通过 dtype
关键字、传递的 ndarray
或传递的 Series
),则在 DataFrame 操作中将保留该数据类型。此外,不同的数值数据类型将不会被合并。以下示例将让您一窥其中。
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
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]
数据类型陷阱
平台陷阱
从 0.11.0 开始,构建 DataFrame/Series 将使用 int64
和 float64
的默认数据类型,不受平台影响。这与 pandas 早期版本没有明显变化。如果指定了数据类型,它们将被尊重,但是(GH 2837)
以下都将导致 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
请记住,在 32 位平台上,DataFrame(np.array([1,2]))
将导致 int32
!
向上转换的陷阱
在整数类型数据上执行索引操作可能会轻松向上转换数据。在不引入 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
日期时间转换
DataFrame(或 Series)中的 Datetime64[ns] 列允许使用 np.nan
表示 nan 值,除了传统的 NaT
或非时间值。这允许以通用方式设置 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[s] 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[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()
方法,以便于创建索引器(GH 3275)HDFStore
- 添加了
select_column
方法,用于从表中选择单列作为 Series。- 废弃了
unique
方法,可以通过select_column(key,column).unique()
复制append
的min_itemsize
参数现在会自动为传递的键创建 data_columns
增强功能
在某些情况下,通过最多��高 10 倍来改进 df.to_csv() 的性能。(GH 3059)
Numexpr 现在是推荐依赖项,用于加速某些类型的数值和布尔操作
Bottleneck 现在是推荐依赖项,用于加速某些类型的
nan
操作
HDFStore
支持类似于
read_csv/to_csv
的read_hdf/to_hdf
APIIn [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
为
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
。也适用于未来到期月份,并将实例变量保存为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 现在不仅接受字典,还接受任何 collections.Mapping ABC 的实例。
添加了选项
display.mpl_style
,为图表提供更加时尚的视觉风格。基于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
选择选项
从 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 开始,这些方法 可能 在未来的版本中被弃用。
-
irow
-
icol
-
iget_value
请参阅按位置选择部分以获取替代方法。
Dtype
数值 dtype 将会传播,并且可以在 DataFrame 中共存。如果传递了 dtype(可以直接通过 dtype
关键字,通过传递的 ndarray
,或传递的 Series
),则它将在 DataFrame 操作中被保留。此外,不同的数值 dtype 将 不会 被合并。以下示例会让你领略一番。
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
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
!
向上转换的注意事项
在整数类型数据上执行索引操作很容易将数据向上转换。在未引入 nans
的情况下,输入数据的 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
浮点数的 dtype 保持不变。
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
,或非时间。这使得以一种通用的方式方便地设置 nan 成为可能。此外,当传递 datetimelike 对象时,默认情况下会创建 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[s] 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]
的 astype
转换为 object
,会隐式地将 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[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()
方法到索引中,以便创建索引器(GH 3275)HDFStore
- 添加了
select_column
方法,以选择表中的单个列作为 Series。- 弃用了
unique
方法,可以通过select_column(key,column).unique()
复制append
方法的min_itemsize
参数现在会自动为传递的键创建数据列
增强功能
df.to_csv() 的性能提升最多可达 10 倍。(GH 3059)
Numexpr 现在是一个推荐的依赖项,用于加速某些类型的数值和布尔操作
Bottleneck 现在是 推荐的依赖项,以加速某些类型的
nan
操作
HDFStore
支持与
read_csv/to_csv
类似的read_hdf/to_hdf
APIIn [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.df == store['df']
提供了新的关键字
iterator=boolean
和chunksize=number_in_a_chunk
来支持对select
和select_as_multiple
进行迭代(GH 3076)现在你可以像对待 有序 时间序列一样,从 无序 时间序列中选择时间戳(GH 2437)
现在你可以像对待 Series 一样,从具有日期索引的 DataFrame 中选择字符串(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
来防止对超过 1M 行的框架计算详细信息(可配置)。(GH 2807, GH 2918)value_counts() 现在接受一个 "normalize" 参数,用于归一化直方图。(GH 2710)。
DataFrame.from_records 现在不仅接受字典,而且接受任何 collections.Mapping ABC 的实例。
添加了选项
display.mpl_style
,为绘图提供了更简洁的视觉风格。基于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