forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathv0.15.0.txt
1138 lines (800 loc) · 50.4 KB
/
v0.15.0.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
.. _whatsnew_0150:
v0.15.0 (October 18, 2014)
--------------------------
This is a major release from 0.14.1 and includes a small number of API changes, several new features,
enhancements, and performance improvements along with a large number of bug fixes. We recommend that all
users upgrade to this version.
.. warning::
pandas >= 0.15.0 will no longer support compatibility with NumPy versions <
1.7.0. If you want to use the latest versions of pandas, please upgrade to
NumPy >= 1.7.0 (:issue:`7711`)
- Highlights include:
- The ``Categorical`` type was integrated as a first-class pandas type, see :ref:`here <whatsnew_0150.cat>`
- New scalar type ``Timedelta``, and a new index type ``TimedeltaIndex``, see :ref:`here <whatsnew_0150.timedeltaindex>`
- New datetimelike properties accessor ``.dt`` for Series, see :ref:`Datetimelike Properties <whatsnew_0150.dt>`
- New DataFrame default display for ``df.info()`` to include memory usage, see :ref:`Memory Usage <whatsnew_0150.memory>`
- ``read_csv`` will now by default ignore blank lines when parsing, see :ref:`here <whatsnew_0150.blanklines>`
- API change in using Indexes in set operations, see :ref:`here <whatsnew_0150.index_set_ops>`
- Enhancements in the handling of timezones, see :ref:`here <whatsnew_0150.tz>`
- A lot of improvements to the rolling and expanding moment funtions, see :ref:`here <whatsnew_0150.roll>`
- Internal refactoring of the ``Index`` class to no longer sub-class ``ndarray``, see :ref:`Internal Refactoring <whatsnew_0150.refactoring>`
- dropping support for ``PyTables`` less than version 3.0.0, and ``numexpr`` less than version 2.1 (:issue:`7990`)
- Split indexing documentation into :ref:`Indexing and Selecting Data <indexing>` and :ref:`MultiIndex / Advanced Indexing <advanced>`
- Split out string methods documentation into :ref:`Working with Text Data <text>`
- Check the :ref:`API Changes <whatsnew_0150.api>` and :ref:`deprecations <whatsnew_0150.deprecations>` before updating
- :ref:`Other Enhancements <whatsnew_0150.enhancements>`
- :ref:`Performance Improvements <whatsnew_0150.performance>`
- :ref:`Bug Fixes <whatsnew_0150.bug_fixes>`
.. warning::
In 0.15.0 ``Index`` has internally been refactored to no longer sub-class ``ndarray``
but instead subclass ``PandasObject``, similarly to the rest of the pandas objects. This change allows very easy sub-classing and creation of new index types. This should be
a transparent change with only very limited API implications (See the :ref:`Internal Refactoring <whatsnew_0150.refactoring>`)
.. warning::
The refactorings in :class:`~pandas.Categorical` changed the two argument constructor from
"codes/labels and levels" to "values and levels (now called 'categories')". This can lead to subtle bugs. If you use
:class:`~pandas.Categorical` directly, please audit your code before updating to this pandas
version and change it to use the :meth:`~pandas.Categorical.from_codes` constructor. See more on ``Categorical`` :ref:`here <whatsnew_0150.cat>`
New features
~~~~~~~~~~~~
.. _whatsnew_0150.cat:
Categoricals in Series/DataFrame
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:class:`~pandas.Categorical` can now be included in `Series` and `DataFrames` and gained new
methods to manipulate. Thanks to Jan Schulz for much of this API/implementation. (:issue:`3943`, :issue:`5313`, :issue:`5314`,
:issue:`7444`, :issue:`7839`, :issue:`7848`, :issue:`7864`, :issue:`7914`, :issue:`7768`, :issue:`8006`, :issue:`3678`,
:issue:`8075`, :issue:`8076`, :issue:`8143`, :issue:`8453`, :issue:`8518`).
For full docs, see the :ref:`categorical introduction <categorical>` and the
:ref:`API documentation <api.categorical>`.
.. ipython:: python
df = DataFrame({"id":[1,2,3,4,5,6], "raw_grade":['a', 'b', 'b', 'a', 'a', 'e']})
df["grade"] = df["raw_grade"].astype("category")
df["grade"]
# Rename the categories
df["grade"].cat.categories = ["very good", "good", "very bad"]
# Reorder the categories and simultaneously add the missing categories
df["grade"] = df["grade"].cat.set_categories(["very bad", "bad", "medium", "good", "very good"])
df["grade"]
df.sort("grade")
df.groupby("grade").size()
- ``pandas.core.group_agg`` and ``pandas.core.factor_agg`` were removed. As an alternative, construct
a dataframe and use ``df.groupby(<group>).agg(<func>)``.
- Supplying "codes/labels and levels" to the :class:`~pandas.Categorical` constructor is not
supported anymore. Supplying two arguments to the constructor is now interpreted as
"values and levels (now called 'categories')". Please change your code to use the :meth:`~pandas.Categorical.from_codes`
constructor.
- The ``Categorical.labels`` attribute was renamed to ``Categorical.codes`` and is read
only. If you want to manipulate codes, please use one of the
:ref:`API methods on Categoricals <api.categorical>`.
- The ``Categorical.levels`` attribute is renamed to ``Categorical.categories``.
.. _whatsnew_0150.timedeltaindex:
TimedeltaIndex/Scalar
^^^^^^^^^^^^^^^^^^^^^
We introduce a new scalar type ``Timedelta``, which is a subclass of ``datetime.timedelta``, and behaves in a similar manner,
but allows compatibility with ``np.timedelta64`` types as well as a host of custom representation, parsing, and attributes.
This type is very similar to how ``Timestamp`` works for ``datetimes``. It is a nice-API box for the type. See the :ref:`docs <timedeltas.timedeltas>`.
(:issue:`3009`, :issue:`4533`, :issue:`8209`, :issue:`8187`, :issue:`8190`, :issue:`7869`, :issue:`7661`, :issue:`8345`, :issue:`8471`)
.. warning::
``Timedelta`` scalars (and ``TimedeltaIndex``) component fields are *not the same* as the component fields on a ``datetime.timedelta`` object. For example, ``.seconds`` on a ``datetime.timedelta`` object returns the total number of seconds combined between ``hours``, ``minutes`` and ``seconds``. In contrast, the pandas ``Timedelta`` breaks out hours, minutes, microseconds and nanoseconds separately.
.. ipython:: python
# Timedelta accessor
tds = Timedelta('31 days 5 min 3 sec')
tds.minutes
tds.seconds
# datetime.timedelta accessor
# this is 5 minutes * 60 + 3 seconds
tds.to_pytimedelta().seconds
.. warning::
Prior to 0.15.0 ``pd.to_timedelta`` would return a ``Series`` for list-like/Series input, and a ``np.timedelta64`` for scalar input.
It will now return a ``TimedeltaIndex`` for list-like input, ``Series`` for Series input, and ``Timedelta`` for scalar input.
The arguments to ``pd.to_timedelta`` are now ``(arg,unit='ns',box=True,coerce=False)``, previously were ``(arg,box=True,unit='ns')`` as these are more logical.
Consruct a scalar
.. ipython:: python
Timedelta('1 days 06:05:01.00003')
Timedelta('15.5us')
Timedelta('1 hour 15.5us')
# negative Timedeltas have this string repr
# to be more consistent with datetime.timedelta conventions
Timedelta('-1us')
# a NaT
Timedelta('nan')
Access fields for a ``Timedelta``
.. ipython:: python
td = Timedelta('1 hour 3m 15.5us')
td.hours
td.minutes
td.microseconds
td.nanoseconds
Construct a ``TimedeltaIndex``
.. ipython:: python
:suppress:
import datetime
from datetime import timedelta
.. ipython:: python
TimedeltaIndex(['1 days','1 days, 00:00:05',
np.timedelta64(2,'D'),timedelta(days=2,seconds=2)])
Constructing a ``TimedeltaIndex`` with a regular range
.. ipython:: python
timedelta_range('1 days',periods=5,freq='D')
timedelta_range(start='1 days',end='2 days',freq='30T')
You can now use a ``TimedeltaIndex`` as the index of a pandas object
.. ipython:: python
s = Series(np.arange(5),
index=timedelta_range('1 days',periods=5,freq='s'))
s
You can select with partial string selections
.. ipython:: python
s['1 day 00:00:02']
s['1 day':'1 day 00:00:02']
Finally, the combination of ``TimedeltaIndex`` with ``DatetimeIndex`` allow certain combination operations that are ``NaT`` preserving:
.. ipython:: python
tdi = TimedeltaIndex(['1 days',pd.NaT,'2 days'])
tdi.tolist()
dti = date_range('20130101',periods=3)
dti.tolist()
(dti + tdi).tolist()
(dti - tdi).tolist()
- iteration of a ``Series`` e.g. ``list(Series(...))`` of ``timedelta64[ns]`` would prior to v0.15.0 return ``np.timedelta64`` for each element. These will now be wrapped in ``Timedelta``.
.. _whatsnew_0150.memory:
Memory Usage
^^^^^^^^^^^^
Implemented methods to find memory usage of a DataFrame. See the :ref:`FAQ <df-memory-usage>` for more. (:issue:`6852`).
A new display option ``display.memory_usage`` (see :ref:`options`) sets the default behavior of the ``memory_usage`` argument in the ``df.info()`` method. By default ``display.memory_usage`` is ``True``.
.. ipython:: python
dtypes = ['int64', 'float64', 'datetime64[ns]', 'timedelta64[ns]',
'complex128', 'object', 'bool']
n = 5000
data = dict([ (t, np.random.randint(100, size=n).astype(t))
for t in dtypes])
df = DataFrame(data)
df['categorical'] = df['object'].astype('category')
df.info()
Additionally :meth:`~pandas.DataFrame.memory_usage` is an available method for a dataframe object which returns the memory usage of each column.
.. ipython:: python
df.memory_usage(index=True)
.. _whatsnew_0150.dt:
.dt accessor
^^^^^^^^^^^^
``Series`` has gained an accessor to succinctly return datetime like properties for the *values* of the Series, if its a datetime/period like Series. (:issue:`7207`)
This will return a Series, indexed like the existing Series. See the :ref:`docs <basics.dt_accessors>`
.. ipython:: python
# datetime
s = Series(date_range('20130101 09:10:12',periods=4))
s
s.dt.hour
s.dt.second
s.dt.day
s.dt.freq
This enables nice expressions like this:
.. ipython:: python
s[s.dt.day==2]
You can easily produce tz aware transformations:
.. ipython:: python
stz = s.dt.tz_localize('US/Eastern')
stz
stz.dt.tz
You can also chain these types of operations:
.. ipython:: python
s.dt.tz_localize('UTC').dt.tz_convert('US/Eastern')
The ``.dt`` accessor works for period and timedelta dtypes.
.. ipython:: python
# period
s = Series(period_range('20130101',periods=4,freq='D'))
s
s.dt.year
s.dt.day
.. ipython:: python
# timedelta
s = Series(timedelta_range('1 day 00:00:05',periods=4,freq='s'))
s
s.dt.days
s.dt.seconds
s.dt.components
.. _whatsnew_0150.tz:
Timezone handling improvements
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- ``tz_localize(None)`` for tz-aware ``Timestamp`` and ``DatetimeIndex`` now removes timezone holding local time,
previously this resulted in ``Exception`` or ``TypeError`` (:issue:`7812`)
.. ipython:: python
ts = Timestamp('2014-08-01 09:00', tz='US/Eastern')
ts
ts.tz_localize(None)
didx = DatetimeIndex(start='2014-08-01 09:00', freq='H', periods=10, tz='US/Eastern')
didx
didx.tz_localize(None)
- ``tz_localize`` now accepts the ``ambiguous`` keyword which allows for passing an array of bools
indicating whether the date belongs in DST or not, 'NaT' for setting transition times to NaT,
'infer' for inferring DST/non-DST, and 'raise' (default) for an ``AmbiguousTimeError`` to be raised. See :ref:`the docs<timeseries.timezone_ambiguous>` for more details (:issue:`7943`)
- ``DataFrame.tz_localize`` and ``DataFrame.tz_convert`` now accepts an optional ``level`` argument
for localizing a specific level of a MultiIndex (:issue:`7846`)
- ``Timestamp.tz_localize`` and ``Timestamp.tz_convert`` now raise ``TypeError`` in error cases, rather than ``Exception`` (:issue:`8025`)
- a timeseries/index localized to UTC when inserted into a Series/DataFrame will preserve the UTC timezone (rather than being a naive ``datetime64[ns]``) as ``object`` dtype (:issue:`8411`)
- ``Timestamp.__repr__`` displays ``dateutil.tz.tzoffset`` info (:issue:`7907`)
.. _whatsnew_0150.roll:
Rolling/Expanding Moments improvements
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- :func:`rolling_min`, :func:`rolling_max`, :func:`rolling_cov`, and :func:`rolling_corr`
now return objects with all ``NaN`` when ``len(arg) < min_periods <= window`` rather
than raising. (This makes all rolling functions consistent in this behavior). (:issue:`7766`)
Prior to 0.15.0
.. ipython:: python
s = Series([10, 11, 12, 13])
.. code-block:: python
In [15]: rolling_min(s, window=10, min_periods=5)
ValueError: min_periods (5) must be <= window (4)
New behavior
.. ipython:: python
rolling_min(s, window=10, min_periods=5)
- :func:`rolling_max`, :func:`rolling_min`, :func:`rolling_sum`, :func:`rolling_mean`, :func:`rolling_median`,
:func:`rolling_std`, :func:`rolling_var`, :func:`rolling_skew`, :func:`rolling_kurt`, :func:`rolling_quantile`,
:func:`rolling_cov`, :func:`rolling_corr`, :func:`rolling_corr_pairwise`,
:func:`rolling_window`, and :func:`rolling_apply` with ``center=True`` previously would return a result of the same
structure as the input ``arg`` with ``NaN`` in the final ``(window-1)/2`` entries.
Now the final ``(window-1)/2`` entries of the result are calculated as if the input ``arg`` were followed
by ``(window-1)/2`` ``NaN`` values (or with shrinking windows, in the case of :func:`rolling_apply`).
(:issue:`7925`, :issue:`8269`)
Prior behavior (note final value is ``NaN``):
.. code-block:: python
In [7]: rolling_sum(Series(range(4)), window=3, min_periods=0, center=True)
Out[7]:
0 1
1 3
2 6
3 NaN
dtype: float64
New behavior (note final value is ``5 = sum([2, 3, NaN])``):
.. ipython:: python
rolling_sum(Series(range(4)), window=3, min_periods=0, center=True)
- :func:`rolling_window` now normalizes the weights properly in rolling mean mode (`mean=True`) so that
the calculated weighted means (e.g. 'triang', 'gaussian') are distributed about the same means as those
calculated without weighting (i.e. 'boxcar'). See :ref:`the note on normalization <stats.moments.normalization>` for further details. (:issue:`7618`)
.. ipython:: python
s = Series([10.5, 8.8, 11.4, 9.7, 9.3])
Behavior prior to 0.15.0:
.. code-block:: python
In [39]: rolling_window(s, window=3, win_type='triang', center=True)
Out[39]:
0 NaN
1 6.583333
2 6.883333
3 6.683333
4 NaN
dtype: float64
New behavior
.. ipython:: python
rolling_window(s, window=3, win_type='triang', center=True)
- Removed ``center`` argument from all :func:`expanding_ <expanding_apply>` functions (see :ref:`list <api.functions_expanding>`),
as the results produced when ``center=True`` did not make much sense. (:issue:`7925`)
- Added optional ``ddof`` argument to :func:`expanding_cov` and :func:`rolling_cov`.
The default value of ``1`` is backwards-compatible. (:issue:`8279`)
- Documented the ``ddof`` argument to :func:`expanding_var`, :func:`expanding_std`,
:func:`rolling_var`, and :func:`rolling_std`. These functions' support of a
``ddof`` argument (with a default value of ``1``) was previously undocumented. (:issue:`8064`)
- :func:`ewma`, :func:`ewmstd`, :func:`ewmvol`, :func:`ewmvar`, :func:`ewmcov`, and :func:`ewmcorr`
now interpret ``min_periods`` in the same manner that the :func:`rolling_*()` and :func:`expanding_*()` functions do:
a given result entry will be ``NaN`` if the (expanding, in this case) window does not contain
at least ``min_periods`` values. The previous behavior was to set to ``NaN`` the ``min_periods`` entries
starting with the first non- ``NaN`` value. (:issue:`7977`)
Prior behavior (note values start at index ``2``, which is ``min_periods`` after index ``0``
(the index of the first non-empty value)):
.. ipython:: python
s = Series([1, None, None, None, 2, 3])
.. code-block:: python
In [51]: ewma(s, com=3., min_periods=2)
Out[51]:
0 NaN
1 NaN
2 1.000000
3 1.000000
4 1.571429
5 2.189189
dtype: float64
New behavior (note values start at index ``4``, the location of the 2nd (since ``min_periods=2``) non-empty value):
.. ipython:: python
ewma(s, com=3., min_periods=2)
- :func:`ewmstd`, :func:`ewmvol`, :func:`ewmvar`, :func:`ewmcov`, and :func:`ewmcorr`
now have an optional ``adjust`` argument, just like :func:`ewma` does,
affecting how the weights are calculated.
The default value of ``adjust`` is ``True``, which is backwards-compatible.
See :ref:`Exponentially weighted moment functions <stats.moments.exponentially_weighted>` for details. (:issue:`7911`)
- :func:`ewma`, :func:`ewmstd`, :func:`ewmvol`, :func:`ewmvar`, :func:`ewmcov`, and :func:`ewmcorr`
now have an optional ``ignore_na`` argument.
When ``ignore_na=False`` (the default), missing values are taken into account in the weights calculation.
When ``ignore_na=True`` (which reproduces the pre-0.15.0 behavior), missing values are ignored in the weights calculation.
(:issue:`7543`)
.. ipython:: python
ewma(Series([None, 1., 8.]), com=2.)
ewma(Series([1., None, 8.]), com=2., ignore_na=True) # pre-0.15.0 behavior
ewma(Series([1., None, 8.]), com=2., ignore_na=False) # new default
.. warning::
By default (``ignore_na=False``) the :func:`ewm*()` functions' weights calculation
in the presence of missing values is different than in pre-0.15.0 versions.
To reproduce the pre-0.15.0 calculation of weights in the presence of missing values
one must specify explicitly ``ignore_na=True``.
- Bug in :func:`expanding_cov`, :func:`expanding_corr`, :func:`rolling_cov`, :func:`rolling_cor`, :func:`ewmcov`, and :func:`ewmcorr`
returning results with columns sorted by name and producing an error for non-unique columns;
now handles non-unique columns and returns columns in original order
(except for the case of two DataFrames with ``pairwise=False``, where behavior is unchanged) (:issue:`7542`)
- Bug in :func:`rolling_count` and :func:`expanding_*()` functions unnecessarily producing error message for zero-length data (:issue:`8056`)
- Bug in :func:`rolling_apply` and :func:`expanding_apply` interpreting ``min_periods=0`` as ``min_periods=1`` (:issue:`8080`)
- Bug in :func:`expanding_std` and :func:`expanding_var` for a single value producing a confusing error message (:issue:`7900`)
- Bug in :func:`rolling_std` and :func:`rolling_var` for a single value producing ``0`` rather than ``NaN`` (:issue:`7900`)
- Bug in :func:`ewmstd`, :func:`ewmvol`, :func:`ewmvar`, and :func:`ewmcov`
calculation of de-biasing factors when ``bias=False`` (the default).
Previously an incorrect constant factor was used, based on ``adjust=True``, ``ignore_na=True``,
and an infinite number of observations.
Now a different factor is used for each entry, based on the actual weights
(analogous to the usual ``N/(N-1)`` factor).
In particular, for a single point a value of ``NaN`` is returned when ``bias=False``,
whereas previously a value of (approximately) ``0`` was returned.
For example, consider the following pre-0.15.0 results for ``ewmvar(..., bias=False)``,
and the corresponding debiasing factors:
.. ipython:: python
s = Series([1., 2., 0., 4.])
.. code-block:: python
In [89]: ewmvar(s, com=2., bias=False)
Out[89]:
0 -2.775558e-16
1 3.000000e-01
2 9.556787e-01
3 3.585799e+00
dtype: float64
In [90]: ewmvar(s, com=2., bias=False) / ewmvar(s, com=2., bias=True)
Out[90]:
0 1.25
1 1.25
2 1.25
3 1.25
dtype: float64
Note that entry ``0`` is approximately 0, and the debiasing factors are a constant 1.25.
By comparison, the following 0.15.0 results have a ``NaN`` for entry ``0``,
and the debiasing factors are decreasing (towards 1.25):
.. ipython:: python
ewmvar(s, com=2., bias=False)
ewmvar(s, com=2., bias=False) / ewmvar(s, com=2., bias=True)
See :ref:`Exponentially weighted moment functions <stats.moments.exponentially_weighted>` for details. (:issue:`7912`)
.. _whatsnew_0150.sql:
Improvements in the sql io module
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Added support for a ``chunksize`` parameter to ``to_sql`` function. This allows DataFrame to be written in chunks and avoid packet-size overflow errors (:issue:`8062`).
- Added support for a ``chunksize`` parameter to ``read_sql`` function. Specifying this argument will return an iterator through chunks of the query result (:issue:`2908`).
- Added support for writing ``datetime.date`` and ``datetime.time`` object columns with ``to_sql`` (:issue:`6932`).
- Added support for specifying a ``schema`` to read from/write to with ``read_sql_table`` and ``to_sql`` (:issue:`7441`, :issue:`7952`).
For example:
.. code-block:: python
df.to_sql('table', engine, schema='other_schema')
pd.read_sql_table('table', engine, schema='other_schema')
- Added support for writing ``NaN`` values with ``to_sql`` (:issue:`2754`).
- Added support for writing datetime64 columns with ``to_sql`` for all database flavors (:issue:`7103`).
.. _whatsnew_0150.api:
Backwards incompatible API changes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. _whatsnew_0150.api_breaking:
Breaking changes
^^^^^^^^^^^^^^^^
API changes related to ``Categorical`` (see :ref:`here <whatsnew_0150.cat>`
for more details):
- The ``Categorical`` constructor with two arguments changed from
"codes/labels and levels" to "values and levels (now called 'categories')".
This can lead to subtle bugs. If you use :class:`~pandas.Categorical` directly,
please audit your code by changing it to use the :meth:`~pandas.Categorical.from_codes`
constructor.
An old function call like (prior to 0.15.0):
.. code-block:: python
pd.Categorical([0,1,0,2,1], levels=['a', 'b', 'c'])
will have to adapted to the following to keep the same behaviour:
.. code-block:: python
In [2]: pd.Categorical.from_codes([0,1,0,2,1], categories=['a', 'b', 'c'])
Out[2]:
[a, b, a, c, b]
Categories (3, object): [a, b, c]
API changes related to the introduction of the ``Timedelta`` scalar (see
:ref:`above <whatsnew_0150.timedeltaindex>` for more details):
- Prior to 0.15.0 :func:`to_timedelta` would return a ``Series`` for list-like/Series input,
and a ``np.timedelta64`` for scalar input. It will now return a ``TimedeltaIndex`` for
list-like input, ``Series`` for Series input, and ``Timedelta`` for scalar input.
For API changes related to the rolling and expanding functions, see detailed overview :ref:`above <whatsnew_0150.roll>`.
Other notable API changes:
- Consistency when indexing with ``.loc`` and a list-like indexer when no values are found.
.. ipython:: python
df = DataFrame([['a'],['b']],index=[1,2])
df
In prior versions there was a difference in these two constructs:
- ``df.loc[[3]]`` would return a frame reindexed by 3 (with all ``np.nan`` values)
- ``df.loc[[3],:]`` would raise ``KeyError``.
Both will now raise a ``KeyError``. The rule is that *at least 1* indexer must be found when using a list-like and ``.loc`` (:issue:`7999`)
Furthermore in prior versions these were also different:
- ``df.loc[[1,3]]`` would return a frame reindexed by [1,3]
- ``df.loc[[1,3],:]`` would raise ``KeyError``.
Both will now return a frame reindex by [1,3]. E.g.
.. ipython:: python
df.loc[[1,3]]
df.loc[[1,3],:]
This can also be seen in multi-axis indexing with a ``Panel``.
.. ipython:: python
p = Panel(np.arange(2*3*4).reshape(2,3,4),
items=['ItemA','ItemB'],
major_axis=[1,2,3],
minor_axis=['A','B','C','D'])
p
The following would raise ``KeyError`` prior to 0.15.0:
.. ipython:: python
p.loc[['ItemA','ItemD'],:,'D']
Furthermore, ``.loc`` will raise If no values are found in a multi-index with a list-like indexer:
.. ipython:: python
:okexcept:
s = Series(np.arange(3,dtype='int64'),
index=MultiIndex.from_product([['A'],['foo','bar','baz']],
names=['one','two'])
).sortlevel()
s
try:
s.loc[['D']]
except KeyError as e:
print("KeyError: " + str(e))
- Assigning values to ``None`` now considers the dtype when choosing an 'empty' value (:issue:`7941`).
Previously, assigning to ``None`` in numeric containers changed the
dtype to object (or errored, depending on the call). It now uses
``NaN``:
.. ipython:: python
s = Series([1, 2, 3])
s.loc[0] = None
s
``NaT`` is now used similarly for datetime containers.
For object containers, we now preserve ``None`` values (previously these
were converted to ``NaN`` values).
.. ipython:: python
s = Series(["a", "b", "c"])
s.loc[0] = None
s
To insert a ``NaN``, you must explicitly use ``np.nan``. See the :ref:`docs <missing.inserting>`.
- In prior versions, updating a pandas object inplace would not reflect in other python references to this object. (:issue:`8511`, :issue:`5104`)
.. ipython:: python
s = Series([1, 2, 3])
s2 = s
s += 1.5
Behavior prior to v0.15.0
.. code-block:: python
# the original object
In [5]: s
Out[5]:
0 2.5
1 3.5
2 4.5
dtype: float64
# a reference to the original object
In [7]: s2
Out[7]:
0 1
1 2
2 3
dtype: int64
This is now the correct behavior
.. ipython:: python
# the original object
s
# a reference to the original object
s2
.. _whatsnew_0150.blanklines:
- Made both the C-based and Python engines for `read_csv` and `read_table` ignore empty lines in input as well as
whitespace-filled lines, as long as ``sep`` is not whitespace. This is an API change
that can be controlled by the keyword parameter ``skip_blank_lines``. See :ref:`the docs <io.skiplines>` (:issue:`4466`)
- A timeseries/index localized to UTC when inserted into a Series/DataFrame will preserve the UTC timezone
and inserted as ``object`` dtype rather than being converted to a naive ``datetime64[ns]`` (:issue:`8411`).
- Bug in passing a ``DatetimeIndex`` with a timezone that was not being retained in DataFrame construction from a dict (:issue:`7822`)
In prior versions this would drop the timezone, now it retains the timezone,
but gives a column of ``object`` dtype:
.. ipython:: python
i = date_range('1/1/2011', periods=3, freq='10s', tz = 'US/Eastern')
i
df = DataFrame( {'a' : i } )
df
df.dtypes
Previously this would have yielded a column of ``datetime64`` dtype, but without timezone info.
The behaviour of assigning a column to an existing dataframe as `df['a'] = i`
remains unchanged (this already returned an ``object`` column with a timezone).
- When passing multiple levels to :meth:`~pandas.DataFrame.stack()`, it will now raise a ``ValueError`` when the
levels aren't all level names or all level numbers (:issue:`7660`). See
:ref:`Reshaping by stacking and unstacking <reshaping.stack_multiple>`.
- Raise a ``ValueError`` in ``df.to_hdf`` with 'fixed' format, if ``df`` has non-unique columns as the resulting file will be broken (:issue:`7761`)
- ``SettingWithCopy`` raise/warnings (according to the option ``mode.chained_assignment``) will now be issued when setting a value on a sliced mixed-dtype DataFrame using chained-assignment. (:issue:`7845`, :issue:`7950`)
.. code-block:: python
In [1]: df = DataFrame(np.arange(0,9), columns=['count'])
In [2]: df['group'] = 'b'
In [3]: df.iloc[0:5]['group'] = 'a'
/usr/local/bin/ipython:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
- ``merge``, ``DataFrame.merge``, and ``ordered_merge`` now return the same type
as the ``left`` argument (:issue:`7737`).
- Previously an enlargement with a mixed-dtype frame would act unlike ``.append`` which will preserve dtypes (related :issue:`2578`, :issue:`8176`):
.. ipython:: python
df = DataFrame([[True, 1],[False, 2]],
columns=["female","fitness"])
df
df.dtypes
# dtypes are now preserved
df.loc[2] = df.loc[1]
df
df.dtypes
- ``Series.to_csv()`` now returns a string when ``path=None``, matching the behaviour of ``DataFrame.to_csv()`` (:issue:`8215`).
- ``read_hdf`` now raises ``IOError`` when a file that doesn't exist is passed in. Previously, a new, empty file was created, and a ``KeyError`` raised (:issue:`7715`).
- ``DataFrame.info()`` now ends its output with a newline character (:issue:`8114`)
- Concatenating no objects will now raise a ``ValueError`` rather than a bare ``Exception``.
- Merge errors will now be sub-classes of ``ValueError`` rather than raw ``Exception`` (:issue:`8501`)
- ``DataFrame.plot`` and ``Series.plot`` keywords are now have consistent orders (:issue:`8037`)
.. _whatsnew_0150.refactoring:
Internal Refactoring
^^^^^^^^^^^^^^^^^^^^
In 0.15.0 ``Index`` has internally been refactored to no longer sub-class ``ndarray``
but instead subclass ``PandasObject``, similarly to the rest of the pandas objects. This
change allows very easy sub-classing and creation of new index types. This should be
a transparent change with only very limited API implications (:issue:`5080`, :issue:`7439`, :issue:`7796`, :issue:`8024`, :issue:`8367`, :issue:`7997`, :issue:`8522`):
- you may need to unpickle pandas version < 0.15.0 pickles using ``pd.read_pickle`` rather than ``pickle.load``. See :ref:`pickle docs <io.pickle>`
- when plotting with a ``PeriodIndex``, the matplotlib internal axes will now be arrays of ``Period`` rather than a ``PeriodIndex`` (this is similar to how a ``DatetimeIndex`` passes arrays of ``datetimes`` now)
- MultiIndexes will now raise similary to other pandas objects w.r.t. truth testing, see :ref:`here <gotchas.truth>` (:issue:`7897`).
- When plotting a DatetimeIndex directly with matplotlib's `plot` function,
the axis labels will no longer be formatted as dates but as integers (the
internal representation of a ``datetime64``). **UPDATE** This is fixed
in 0.15.1, see :ref:`here <whatsnew_0151.datetime64_plotting>`.
.. _whatsnew_0150.deprecations:
Deprecations
^^^^^^^^^^^^
- The attributes ``Categorical`` ``labels`` and ``levels`` attributes are
deprecated and renamed to ``codes`` and ``categories``.
- The ``outtype`` argument to ``pd.DataFrame.to_dict`` has been deprecated in favor of ``orient``. (:issue:`7840`)
- The ``convert_dummies`` method has been deprecated in favor of
``get_dummies`` (:issue:`8140`)
- The ``infer_dst`` argument in ``tz_localize`` will be deprecated in favor of
``ambiguous`` to allow for more flexibility in dealing with DST transitions.
Replace ``infer_dst=True`` with ``ambiguous='infer'`` for the same behavior (:issue:`7943`).
See :ref:`the docs<timeseries.timezone_ambiguous>` for more details.
- The top-level ``pd.value_range`` has been deprecated and can be replaced by ``.describe()`` (:issue:`8481`)
.. _whatsnew_0150.index_set_ops:
- The ``Index`` set operations ``+`` and ``-`` were deprecated in order to provide these for numeric type operations on certain index types. ``+`` can be replaced by ``.union()`` or ``|``, and ``-`` by ``.difference()``. Further the method name ``Index.diff()`` is deprecated and can be replaced by ``Index.difference()`` (:issue:`8226`)
.. code-block:: python
# +
Index(['a','b','c']) + Index(['b','c','d'])
# should be replaced by
Index(['a','b','c']).union(Index(['b','c','d']))
.. code-block:: python
# -
Index(['a','b','c']) - Index(['b','c','d'])
# should be replaced by
Index(['a','b','c']).difference(Index(['b','c','d']))
- The ``infer_types`` argument to :func:`~pandas.read_html` now has no
effect and is deprecated (:issue:`7762`, :issue:`7032`).
.. _whatsnew_0150.prior_deprecations:
Removal of prior version deprecations/changes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Remove ``DataFrame.delevel`` method in favor of ``DataFrame.reset_index``
.. _whatsnew_0150.enhancements:
Enhancements
~~~~~~~~~~~~
Enhancements in the importing/exporting of Stata files:
- Added support for bool, uint8, uint16 and uint32 datatypes in ``to_stata`` (:issue:`7097`, :issue:`7365`)
- Added conversion option when importing Stata files (:issue:`8527`)
- ``DataFrame.to_stata`` and ``StataWriter`` check string length for
compatibility with limitations imposed in dta files where fixed-width
strings must contain 244 or fewer characters. Attempting to write Stata
dta files with strings longer than 244 characters raises a ``ValueError``. (:issue:`7858`)
- ``read_stata`` and ``StataReader`` can import missing data information into a
``DataFrame`` by setting the argument ``convert_missing`` to ``True``. When
using this options, missing values are returned as ``StataMissingValue``
objects and columns containing missing values have ``object`` data type. (:issue:`8045`)
Enhancements in the plotting functions:
- Added ``layout`` keyword to ``DataFrame.plot``. You can pass a tuple of ``(rows, columns)``, one of which can be ``-1`` to automatically infer (:issue:`6667`, :issue:`8071`).
- Allow to pass multiple axes to ``DataFrame.plot``, ``hist`` and ``boxplot`` (:issue:`5353`, :issue:`6970`, :issue:`7069`)
- Added support for ``c``, ``colormap`` and ``colorbar`` arguments for ``DataFrame.plot`` with ``kind='scatter'`` (:issue:`7780`)
- Histogram from ``DataFrame.plot`` with ``kind='hist'`` (:issue:`7809`), See :ref:`the docs<visualization.hist>`.
- Boxplot from ``DataFrame.plot`` with ``kind='box'`` (:issue:`7998`), See :ref:`the docs<visualization.box>`.
Other:
- ``read_csv`` now has a keyword parameter ``float_precision`` which specifies which floating-point converter the C engine should use during parsing, see :ref:`here <io.float_precision>` (:issue:`8002`, :issue:`8044`)
- Added ``searchsorted`` method to ``Series`` objects (:issue:`7447`)
- :func:`describe` on mixed-types DataFrames is more flexible. Type-based column filtering is now possible via the ``include``/``exclude`` arguments.
See the :ref:`docs <basics.describe>` (:issue:`8164`).
.. ipython:: python
df = DataFrame({'catA': ['foo', 'foo', 'bar'] * 8,
'catB': ['a', 'b', 'c', 'd'] * 6,
'numC': np.arange(24),
'numD': np.arange(24.) + .5})
df.describe(include=["object"])
df.describe(include=["number", "object"], exclude=["float"])
Requesting all columns is possible with the shorthand 'all'
.. ipython:: python
df.describe(include='all')
Without those arguments, 'describe` will behave as before, including only numerical columns or, if none are, only categorical columns. See also the :ref:`docs <basics.describe>`
- Added ``split`` as an option to the ``orient`` argument in ``pd.DataFrame.to_dict``. (:issue:`7840`)
- The ``get_dummies`` method can now be used on DataFrames. By default only
catagorical columns are encoded as 0's and 1's, while other columns are
left untouched.
.. ipython:: python
df = DataFrame({'A': ['a', 'b', 'a'], 'B': ['c', 'c', 'b'],
'C': [1, 2, 3]})
pd.get_dummies(df)
- ``PeriodIndex`` supports ``resolution`` as the same as ``DatetimeIndex`` (:issue:`7708`)
- ``pandas.tseries.holiday`` has added support for additional holidays and ways to observe holidays (:issue:`7070`)
- ``pandas.tseries.holiday.Holiday`` now supports a list of offsets in Python3 (:issue:`7070`)
- ``pandas.tseries.holiday.Holiday`` now supports a days_of_week parameter (:issue:`7070`)
- ``GroupBy.nth()`` now supports selecting multiple nth values (:issue:`7910`)
.. ipython:: python
business_dates = date_range(start='4/1/2014', end='6/30/2014', freq='B')
df = DataFrame(1, index=business_dates, columns=['a', 'b'])
# get the first, 4th, and last date index for each month
df.groupby((df.index.year, df.index.month)).nth([0, 3, -1])
- ``Period`` and ``PeriodIndex`` supports addition/subtraction with ``timedelta``-likes (:issue:`7966`)
If ``Period`` freq is ``D``, ``H``, ``T``, ``S``, ``L``, ``U``, ``N``, ``Timedelta``-like can be added if the result can have same freq. Otherwise, only the same ``offsets`` can be added.
.. ipython:: python
idx = pd.period_range('2014-07-01 09:00', periods=5, freq='H')
idx
idx + pd.offsets.Hour(2)
idx + Timedelta('120m')
idx = pd.period_range('2014-07', periods=5, freq='M')
idx
idx + pd.offsets.MonthEnd(3)
- Added experimental compatibility with ``openpyxl`` for versions >= 2.0. The ``DataFrame.to_excel``
method ``engine`` keyword now recognizes ``openpyxl1`` and ``openpyxl2``
which will explicitly require openpyxl v1 and v2 respectively, failing if
the requested version is not available. The ``openpyxl`` engine is a now a
meta-engine that automatically uses whichever version of openpyxl is
installed. (:issue:`7177`)
- ``DataFrame.fillna`` can now accept a ``DataFrame`` as a fill value (:issue:`8377`)
- Passing multiple levels to :meth:`~pandas.DataFrame.stack()` will now work when multiple level
numbers are passed (:issue:`7660`). See
:ref:`Reshaping by stacking and unstacking <reshaping.stack_multiple>`.
- :func:`set_names`, :func:`set_labels`, and :func:`set_levels` methods now take an optional ``level`` keyword argument to all modification of specific level(s) of a MultiIndex. Additionally :func:`set_names` now accepts a scalar string value when operating on an ``Index`` or on a specific level of a ``MultiIndex`` (:issue:`7792`)
.. ipython:: python
idx = MultiIndex.from_product([['a'], range(3), list("pqr")], names=['foo', 'bar', 'baz'])
idx.set_names('qux', level=0)
idx.set_names(['qux','baz'], level=[0,1])
idx.set_levels(['a','b','c'], level='bar')
idx.set_levels([['a','b','c'],[1,2,3]], level=[1,2])
- ``Index.isin`` now supports a ``level`` argument to specify which index level
to use for membership tests (:issue:`7892`, :issue:`7890`)
.. code-block:: python
In [1]: idx = MultiIndex.from_product([[0, 1], ['a', 'b', 'c']])
In [2]: idx.values
Out[2]: array([(0, 'a'), (0, 'b'), (0, 'c'), (1, 'a'), (1, 'b'), (1, 'c')], dtype=object)
In [3]: idx.isin(['a', 'c', 'e'], level=1)
Out[3]: array([ True, False, True, True, False, True], dtype=bool)
- ``Index`` now supports ``duplicated`` and ``drop_duplicates``. (:issue:`4060`)
.. ipython:: python
idx = Index([1, 2, 3, 4, 1, 2])
idx
idx.duplicated()
idx.drop_duplicates()
- add ``copy=True`` argument to ``pd.concat`` to enable pass thru of complete blocks (:issue:`8252`)
- Added support for numpy 1.8+ data types (``bool_``, ``int_``, ``float_``, ``string_``) for conversion to R dataframe (:issue:`8400`)
.. _whatsnew_0150.performance: