forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathv0.19.0.txt
1465 lines (999 loc) · 64 KB
/
v0.19.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_0190:
v0.19.0 (August ??, 2016)
-------------------------
This is a major release from 0.18.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.19.0 will no longer silence numpy ufunc warnings upon import, see :ref:`here <whatsnew_0190.errstate>`.
Highlights include:
- :func:`merge_asof` for asof-style time-series joining, see :ref:`here <whatsnew_0190.enhancements.asof_merge>`
- ``.rolling()`` are now time-series aware, see :ref:`here <whatsnew_0190.enhancements.rolling_ts>`
- pandas development api, see :ref:`here <whatsnew_0190.dev_api>`
- ``PeriodIndex`` now has its own ``period`` dtype, and changed to be more consistent with other ``Index`` classes. See ref:`here <whatsnew_0190.api.period>`
- Sparse data structures now gained enhanced support of ``int`` and ``bool`` dtypes, see :ref:`here <whatsnew_0190.sparse>`
.. contents:: What's new in v0.19.0
:local:
:backlinks: none
.. _whatsnew_0190.new_features:
New features
~~~~~~~~~~~~
.. _whatsnew_0190.dev_api:
pandas development API
^^^^^^^^^^^^^^^^^^^^^^
As part of making pandas APi more uniform and accessible in the future, we have created a standard
sub-package of pandas, ``pandas.api`` to hold public API's. We are starting by exposing type
introspection functions in ``pandas.api.types``. More sub-packages and officially sanctioned API's
will be published in future versions of pandas (:issue:`13147`, :issue:`13634`)
The following are now part of this API:
.. ipython:: python
import pprint
from pandas.api import types
funcs = [ f for f in dir(types) if not f.startswith('_') ]
pprint.pprint(funcs)
.. note::
Calling these functions from the internal module ``pandas.core.common`` will now show a ``DeprecationWarning`` (:issue:`13990`)
.. _whatsnew_0190.enhancements.asof_merge:
``merge_asof`` for asof-style time-series joining
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A long-time requested feature has been added through the :func:`merge_asof` function, to
support asof style joining of time-series. (:issue:`1870`, :issue:`13695`, :issue:`13709`, :issue:`13902`). Full documentation is
:ref:`here <merging.merge_asof>`
The :func:`merge_asof` performs an asof merge, which is similar to a left-join
except that we match on nearest key rather than equal keys.
.. ipython:: python
left = pd.DataFrame({'a': [1, 5, 10],
'left_val': ['a', 'b', 'c']})
right = pd.DataFrame({'a': [1, 2, 3, 6, 7],
'right_val': [1, 2, 3, 6, 7]})
left
right
We typically want to match exactly when possible, and use the most
recent value otherwise.
.. ipython:: python
pd.merge_asof(left, right, on='a')
We can also match rows ONLY with prior data, and not an exact match.
.. ipython:: python
pd.merge_asof(left, right, on='a', allow_exact_matches=False)
In a typical time-series example, we have ``trades`` and ``quotes`` and we want to ``asof-join`` them.
This also illustrates using the ``by`` parameter to group data before merging.
.. ipython:: python
trades = pd.DataFrame({
'time': pd.to_datetime(['20160525 13:30:00.023',
'20160525 13:30:00.038',
'20160525 13:30:00.048',
'20160525 13:30:00.048',
'20160525 13:30:00.048']),
'ticker': ['MSFT', 'MSFT',
'GOOG', 'GOOG', 'AAPL'],
'price': [51.95, 51.95,
720.77, 720.92, 98.00],
'quantity': [75, 155,
100, 100, 100]},
columns=['time', 'ticker', 'price', 'quantity'])
quotes = pd.DataFrame({
'time': pd.to_datetime(['20160525 13:30:00.023',
'20160525 13:30:00.023',
'20160525 13:30:00.030',
'20160525 13:30:00.041',
'20160525 13:30:00.048',
'20160525 13:30:00.049',
'20160525 13:30:00.072',
'20160525 13:30:00.075']),
'ticker': ['GOOG', 'MSFT', 'MSFT',
'MSFT', 'GOOG', 'AAPL', 'GOOG',
'MSFT'],
'bid': [720.50, 51.95, 51.97, 51.99,
720.50, 97.99, 720.50, 52.01],
'ask': [720.93, 51.96, 51.98, 52.00,
720.93, 98.01, 720.88, 52.03]},
columns=['time', 'ticker', 'bid', 'ask'])
.. ipython:: python
trades
quotes
An asof merge joins on the ``on``, typically a datetimelike field, which is ordered, and
in this case we are using a grouper in the ``by`` field. This is like a left-outer join, except
that forward filling happens automatically taking the most recent non-NaN value.
.. ipython:: python
pd.merge_asof(trades, quotes,
on='time',
by='ticker')
This returns a merged DataFrame with the entries in the same order as the original left
passed DataFrame (``trades`` in this case), with the fields of the ``quotes`` merged.
.. _whatsnew_0190.enhancements.rolling_ts:
``.rolling()`` are now time-series aware
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
``.rolling()`` objects are now time-series aware and can accept a time-series offset (or convertible) for the ``window`` argument (:issue:`13327`, :issue:`12995`)
See the full documentation :ref:`here <stats.moments.ts>`.
.. ipython:: python
dft = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]},
index=pd.date_range('20130101 09:00:00', periods=5, freq='s'))
dft
This is a regular frequency index. Using an integer window parameter works to roll along the window frequency.
.. ipython:: python
dft.rolling(2).sum()
dft.rolling(2, min_periods=1).sum()
Specifying an offset allows a more intuitive specification of the rolling frequency.
.. ipython:: python
dft.rolling('2s').sum()
Using a non-regular, but still monotonic index, rolling with an integer window does not impart any special calculation.
.. ipython:: python
dft = DataFrame({'B': [0, 1, 2, np.nan, 4]},
index = pd.Index([pd.Timestamp('20130101 09:00:00'),
pd.Timestamp('20130101 09:00:02'),
pd.Timestamp('20130101 09:00:03'),
pd.Timestamp('20130101 09:00:05'),
pd.Timestamp('20130101 09:00:06')],
name='foo'))
dft
dft.rolling(2).sum()
Using the time-specification generates variable windows for this sparse data.
.. ipython:: python
dft.rolling('2s').sum()
Furthermore, we now allow an optional ``on`` parameter to specify a column (rather than the
default of the index) in a DataFrame.
.. ipython:: python
dft = dft.reset_index()
dft
dft.rolling('2s', on='foo').sum()
.. _whatsnew_0190.enhancements.read_csv_dupe_col_names_support:
``read_csv`` has improved support for duplicate column names
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. ipython:: python
:suppress:
from pandas.compat import StringIO
:ref:`Duplicate column names <io.dupe_names>` are now supported in :func:`read_csv` whether
they are in the file or passed in as the ``names`` parameter (:issue:`7160`, :issue:`9424`)
.. ipython :: python
data = '0,1,2\n3,4,5'
names = ['a', 'b', 'a']
Previous behaviour:
.. code-block:: ipython
In [2]: pd.read_csv(StringIO(data), names=names)
Out[2]:
a b a
0 2 1 2
1 5 4 5
The first 'a' column contains the same data as the second 'a' column, when it should have
contained the array ``[0, 3]``.
New behaviour:
.. ipython :: python
In [2]: pd.read_csv(StringIO(data), names=names)
.. _whatsnew_0190.enhancements.read_csv_categorical:
:func:`read_csv` supports parsing ``Categorical`` directly
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The :func:`read_csv` function now supports parsing a ``Categorical`` column when
specified as a dtype (:issue:`10153`). Depending on the structure of the data,
this can result in a faster parse time and lower memory usage compared to
converting to ``Categorical`` after parsing. See the io :ref:`docs here <io.categorical>`
.. ipython:: python
data = 'col1,col2,col3\na,b,1\na,b,2\nc,d,3'
pd.read_csv(StringIO(data))
pd.read_csv(StringIO(data)).dtypes
pd.read_csv(StringIO(data), dtype='category').dtypes
Individual columns can be parsed as a ``Categorical`` using a dict specification
.. ipython:: python
pd.read_csv(StringIO(data), dtype={'col1': 'category'}).dtypes
.. note::
The resulting categories will always be parsed as strings (object dtype).
If the categories are numeric they can be converted using the
:func:`to_numeric` function, or as appropriate, another converter
such as :func:`to_datetime`.
.. ipython:: python
df = pd.read_csv(StringIO(data), dtype='category')
df.dtypes
df['col3']
df['col3'].cat.categories = pd.to_numeric(df['col3'].cat.categories)
df['col3']
.. _whatsnew_0190.enhancements.semi_month_offsets:
Semi-Month Offsets
^^^^^^^^^^^^^^^^^^
Pandas has gained new frequency offsets, ``SemiMonthEnd`` ('SM') and ``SemiMonthBegin`` ('SMS').
These provide date offsets anchored (by default) to the 15th and end of month, and 15th and 1st of month respectively.
(:issue:`1543`)
.. ipython:: python
from pandas.tseries.offsets import SemiMonthEnd, SemiMonthBegin
SemiMonthEnd:
.. ipython:: python
Timestamp('2016-01-01') + SemiMonthEnd()
pd.date_range('2015-01-01', freq='SM', periods=4)
SemiMonthBegin:
.. ipython:: python
Timestamp('2016-01-01') + SemiMonthBegin()
pd.date_range('2015-01-01', freq='SMS', periods=4)
Using the anchoring suffix, you can also specify the day of month to use instead of the 15th.
.. ipython:: python
pd.date_range('2015-01-01', freq='SMS-16', periods=4)
pd.date_range('2015-01-01', freq='SM-14', periods=4)
.. _whatsnew_0190.enhancements.index:
New Index methods
^^^^^^^^^^^^^^^^^
Following methods and options are added to ``Index`` to be more consistent with ``Series`` and ``DataFrame``.
``Index`` now supports the ``.where()`` function for same shape indexing (:issue:`13170`)
.. ipython:: python
idx = pd.Index(['a', 'b', 'c'])
idx.where([True, False, True])
``Index`` now supports ``.dropna`` to exclude missing values (:issue:`6194`)
.. ipython:: python
idx = pd.Index([1, 2, np.nan, 4])
idx.dropna()
For ``MultiIndex``, values are dropped if any level is missing by default. Specifying
``how='all'`` only drops values where all levels are missing.
.. ipython:: python
midx = pd.MultiIndex.from_arrays([[1, 2, np.nan, 4],
[1, 2, np.nan, np.nan]])
midx
midx.dropna()
midx.dropna(how='all')
``Index`` now supports ``.str.extractall()`` which returns a ``DataFrame``, the see :ref:`docs here <text.extractall>` (:issue:`10008`, :issue:`13156`)
.. ipython:: python
idx = pd.Index(["a1a2", "b1", "c1"])
idx.str.extractall("[ab](?P<digit>\d)")
``Index.astype()`` now accepts an optional boolean argument ``copy``, which allows optional copying if the requirements on dtype are satisfied (:issue:`13209`)
.. _whatsnew_0190.gbq:
Google BigQuery Enhancements
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- The :func:`pandas.io.gbq.read_gbq` method has gained the ``dialect`` argument to allow users to specify whether to use BigQuery's legacy SQL or BigQuery's standard SQL. See the :ref:`docs <io.bigquery_reader>` for more details (:issue:`13615`).
.. _whatsnew_0190.errstate:
Fine-grained numpy errstate
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Previous versions of pandas would permanently silence numpy's ufunc error handling when ``pandas`` was imported. Pandas did this in order to silence the warnings that would arise from using numpy ufuncs on missing data, which are usually represented as ``NaN`` s. Unfortunately, this silenced legitimate warnings arising in non-pandas code in the application. Starting with 0.19.0, pandas will use the ``numpy.errstate`` context manager to silence these warnings in a more fine-grained manner, only around where these operations are actually used in the pandas codebase. (:issue:`13109`, :issue:`13145`)
After upgrading pandas, you may see *new* ``RuntimeWarnings`` being issued from your code. These are likely legitimate, and the underlying cause likely existed in the code when using previous versions of pandas that simply silenced the warning. Use `numpy.errstate <http://docs.scipy.org/doc/numpy/reference/generated/numpy.errstate.html>`__ around the source of the ``RuntimeWarning`` to control how these conditions are handled.
.. _whatsnew_0190.get_dummies_dtypes:
get_dummies dtypes
^^^^^^^^^^^^^^^^^^
The ``pd.get_dummies`` function now returns dummy-encoded columns as small integers, rather than floats (:issue:`8725`)
Previous behaviour:
.. code-block:: ipython
In [1]: pd.get_dummies(['a', 'b', 'a', 'c']).dtypes
Out[1]:
a float64
b float64
c float64
dtype: object
New Behavior:
.. ipython:: python
pd.get_dummies(['a', 'b', 'a', 'c']).dtypes
.. _whatsnew_0190.enhancements.other:
Other enhancements
^^^^^^^^^^^^^^^^^^
- The ``.get_credentials()`` method of ``GbqConnector`` can now first try to fetch [the application default credentials](https://developers.google.com/identity/protocols/application-default-credentials). See the :ref:`docs <io.bigquery_authentication>` for more details (:issue:`13577`).
- The ``.tz_localize()`` method of ``DatetimeIndex`` and ``Timestamp`` has gained the ``errors`` keyword, so you can potentially coerce nonexistent timestamps to ``NaT``. The default behaviour remains to raising a ``NonExistentTimeError`` (:issue:`13057`)
- ``pd.to_numeric()`` now accepts a ``downcast`` parameter, which will downcast the data if possible to smallest specified numerical dtype (:issue:`13352`)
.. ipython:: python
s = ['1', 2, 3]
pd.to_numeric(s, downcast='unsigned')
pd.to_numeric(s, downcast='integer')
- ``.to_hdf/read_hdf()`` now accept path objects (e.g. ``pathlib.Path``, ``py.path.local``) for the file path (:issue:`11773`)
- ``Timestamp`` can now accept positional and keyword parameters similar to :func:`datetime.datetime` (:issue:`10758`, :issue:`11630`)
.. ipython:: python
pd.Timestamp(2012, 1, 1)
pd.Timestamp(year=2012, month=1, day=1, hour=8, minute=30)
- the ``.resample()`` function now accepts a ``on=`` or ``level=`` parameter for resampling on a datetimelike column or ``MultiIndex`` level (:issue:`13500`)
.. ipython:: python
df = pd.DataFrame({'date': pd.date_range('2015-01-01', freq='W', periods=5),
'a': np.arange(5)},
index=pd.MultiIndex.from_arrays([
[1,2,3,4,5],
pd.date_range('2015-01-01', freq='W', periods=5)],
names=['v','d']))
df
df.resample('M', on='date').sum()
df.resample('M', level='d').sum()
- The ``pd.read_csv()`` with ``engine='python'`` has gained support for the ``decimal`` option (:issue:`12933`)
- The ``pd.read_csv()`` with ``engine='python'`` has gained support for the ``na_filter`` option (:issue:`13321`)
- The ``pd.read_csv()`` with ``engine='python'`` has gained support for the ``memory_map`` option (:issue:`13381`)
- Consistent with the Python API, ``pd.read_csv()`` will now interpret ``+inf`` as positive infinity (:issue:`13274`)
- The ``pd.read_html()`` has gained support for the ``na_values``, ``converters``, ``keep_default_na`` options (:issue:`13461`)
- ``Categorical.astype()`` now accepts an optional boolean argument ``copy``, effective when dtype is categorical (:issue:`13209`)
- ``DataFrame`` has gained the ``.asof()`` method to return the last non-NaN values according to the selected subset (:issue:`13358`)
- The ``DataFrame`` constructor will now respect key ordering if a list of ``OrderedDict`` objects are passed in (:issue:`13304`)
- ``pd.read_html()`` has gained support for the ``decimal`` option (:issue:`12907`)
- A function :func:`union_categorical` has been added for combining categoricals, see :ref:`Unioning Categoricals<categorical.union>` (:issue:`13361`, :issue:`:13763`, issue:`13846`)
- ``Series`` has gained the properties ``.is_monotonic``, ``.is_monotonic_increasing``, ``.is_monotonic_decreasing``, similar to ``Index`` (:issue:`13336`)
- ``DataFrame.to_sql()`` now allows a single value as the SQL type for all columns (:issue:`11886`).
- ``Series.append`` now supports the ``ignore_index`` option (:issue:`13677`)
- ``.to_stata()`` and ``StataWriter`` can now write variable labels to Stata dta files using a dictionary to make column names to labels (:issue:`13535`, :issue:`13536`)
- ``.to_stata()`` and ``StataWriter`` will automatically convert ``datetime64[ns]`` columns to Stata format ``%tc``, rather than raising a ``ValueError`` (:issue:`12259`)
- ``read_stata()`` and ``StataReader`` raise with a more explicit error message when reading Stata files with repeated value labels when ``convert_categoricals=True`` (:issue:`13923`)
- ``DataFrame.style`` will now render sparsified MultiIndexes (:issue:`11655`)
- ``DataFrame.style`` will now show column level names (e.g. ``DataFrame.columns.names``) (:issue:`13775`)
- ``DataFrame`` has gained support to re-order the columns based on the values
in a row using ``df.sort_values(by='...', axis=1)`` (:issue:`10806`)
.. ipython:: python
df = pd.DataFrame({'A': [2, 7], 'B': [3, 5], 'C': [4, 8]},
index=['row1', 'row2'])
df.sort_values(by='row2', axis=1)
- Added documentation to :ref:`I/O<io.dtypes>` regarding the perils of reading in columns with mixed dtypes and how to handle it (:issue:`13746`)
- :meth:`~DataFrame.to_html` now has a ``border`` argument to control the value in the opening ``<table>`` tag. The default is the value of the ``html.border`` option, which defaults to 1. This also affects the notebook HTML repr, but since Jupyter's CSS includes a border-width attribute, the visual effect is the same. (:issue:`11563`).
- Raise ``ImportError`` in the sql functions when ``sqlalchemy`` is not installed and a connection string is used (:issue:`11920`).
- Compatibility with matplotlib 2.0. Older versions of pandas should also work with matplotlib 2.0 (:issue:`13333`)
.. _whatsnew_0190.api:
API changes
~~~~~~~~~~~
- ``Timestamp.to_pydatetime`` will issue a ``UserWarning`` when ``warn=True``, and the instance has a non-zero number of nanoseconds (:issue:`14101`)
- ``Panel.to_sparse`` will raise a ``NotImplementedError`` exception when called (:issue:`13778`)
- ``Index.reshape`` will raise a ``NotImplementedError`` exception when called (:issue:`12882`)
- ``pd.read_csv()``, ``pd.read_table()``, and ``pd.read_hdf()`` raise the builtin ``FileNotFoundError`` exception for Python 3.x when called on a nonexistent file, and this is back-ported as IOError in Python 2.x (:issue:`14086`)
- Non-convertible dates in an excel date column will be returned without conversion and the column will be ``object`` dtype, rather than raising an exception (:issue:`10001`)
- ``eval``'s upcasting rules for ``float32`` types have been updated to be more consistent with NumPy's rules. New behavior will not upcast to ``float64`` if you multiply a pandas ``float32`` object by a scalar float64. (:issue:`12388`)
- An ``UnsupportedFunctionCall`` error is now raised if NumPy ufuncs like ``np.mean`` are called on groupby or resample objects (:issue:`12811`)
- Calls to ``.sample()`` will respect the random seed set via ``numpy.random.seed(n)`` (:issue:`13161`)
- ``Styler.apply`` is now more strict about the outputs your function must return. For ``axis=0`` or ``axis=1``, the output shape must be identical. For ``axis=None``, the output must be a DataFrame with identical columns and index labels. (:issue:`13222`)
- ``Float64Index.astype(int)`` will now raise ``ValueError`` if ``Float64Index`` contains ``NaN`` values (:issue:`13149`)
- ``TimedeltaIndex.astype(int)`` and ``DatetimeIndex.astype(int)`` will now return ``Int64Index`` instead of ``np.array`` (:issue:`13209`)
- ``.filter()`` enforces mutual exclusion of the keyword arguments. (:issue:`12399`)
- ``PeridIndex`` can now accept ``list`` and ``array`` which contains ``pd.NaT`` (:issue:`13430`)
- ``__setitem__`` will no longer apply a callable rhs as a function instead of storing it. Call ``where`` directly to get the previous behavior. (:issue:`13299`)
- Passing ``Period`` with multiple frequencies to normal ``Index`` now returns ``Index`` with ``object`` dtype (:issue:`13664`)
- ``PeriodIndex.fillna`` with ``Period`` has different freq now coerces to ``object`` dtype (:issue:`13664`)
- More informative exceptions are passed through the csv parser. The exception type would now be the original exception type instead of ``CParserError``. (:issue:`13652`)
- ``astype()`` will now accept a dict of column name to data types mapping as the ``dtype`` argument. (:issue:`12086`)
- The ``pd.read_json`` and ``DataFrame.to_json`` has gained support for reading and writing json lines with ``lines`` option see :ref:`Line delimited json <io.jsonl>` (:issue:`9180`)
- ``pd.Timedelta(None)`` is now accepted and will return ``NaT``, mirroring ``pd.Timestamp`` (:issue:`13687`)
- ``Timestamp``, ``Period``, ``DatetimeIndex``, ``PeriodIndex`` and ``.dt`` accessor have gained a ``.is_leap_year`` property to check whether the date belongs to a leap year. (:issue:`13727`)
- ``pd.read_hdf`` will now raise a ``ValueError`` instead of ``KeyError``, if a mode other than ``r``, ``r+`` and ``a`` is supplied. (:issue:`13623`)
- ``pd.read_csv()`` in the C engine will now issue a ``ParserWarning`` or raise a ``ValueError`` when ``sep`` encoded is more than one character long (:issue:`14065`)
- ``DataFrame.values`` will now return ``float64`` with a ``DataFrame`` of mixed ``int64`` and ``uint64`` dtypes, conforming to ``np.find_common_type`` (:issue:`10364`, :issue:`13917`)
- ``Series.unique()`` with datetime and timezone now returns return array of ``Timestamp`` with timezone (:issue:`13565`)
.. _whatsnew_0190.api.tolist:
``Series.tolist()`` will now return Python types
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
``Series.tolist()`` will now return Python types in the output, mimicking NumPy ``.tolist()`` behaviour (:issue:`10904`)
.. ipython:: python
s = pd.Series([1,2,3])
type(s.tolist()[0])
Previous Behavior:
.. code-block:: ipython
In [7]: type(s.tolist()[0])
Out[7]:
<class 'numpy.int64'>
New Behavior:
.. ipython:: python
type(s.tolist()[0])
.. _whatsnew_0190.api.series_ops:
``Series`` operators for different indexes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Following ``Series`` operators has been changed to make all operators consistent,
including ``DataFrame`` (:issue:`1134`, :issue:`4581`, :issue:`13538`)
- ``Series`` comparison operators now raise ``ValueError`` when ``index`` are different.
- ``Series`` logical operators align both ``index``.
.. warning::
Until 0.18.1, comparing ``Series`` with the same length has been succeeded even if
these ``index`` are different (the result ignores ``index``). As of 0.19.0, it raises ``ValueError`` to be more strict. This section also describes how to keep previous behaviour or align different indexes using flexible comparison methods like ``.eq``.
As a result, ``Series`` and ``DataFrame`` operators behave as below:
Arithmetic operators
""""""""""""""""""""
Arithmetic operators align both ``index`` (no changes).
.. ipython:: python
s1 = pd.Series([1, 2, 3], index=list('ABC'))
s2 = pd.Series([2, 2, 2], index=list('ABD'))
s1 + s2
df1 = pd.DataFrame([1, 2, 3], index=list('ABC'))
df2 = pd.DataFrame([2, 2, 2], index=list('ABD'))
df1 + df2
Comparison operators
""""""""""""""""""""
Comparison operators raise ``ValueError`` when ``index`` are different.
Previous Behavior (``Series``):
``Series`` compares values ignoring ``index`` as long as both lengthes are the same.
.. code-block:: ipython
In [1]: s1 == s2
Out[1]:
A False
B True
C False
dtype: bool
New Behavior (``Series``):
.. code-block:: ipython
In [2]: s1 == s2
Out[2]:
ValueError: Can only compare identically-labeled Series objects
.. note::
To achieve the same result as previous versions (compare values based on locations ignoring ``index``), compare both ``.values``.
.. ipython:: python
s1.values == s2.values
If you want to compare ``Series`` aligning its ``index``, see flexible comparison methods section below.
Current Behavior (``DataFrame``, no change):
.. code-block:: ipython
In [3]: df1 == df2
Out[3]:
ValueError: Can only compare identically-labeled DataFrame objects
Logical operators
"""""""""""""""""
Logical operators align both ``index``.
Previous Behavior (``Series``):
Only left hand side ``index`` is kept.
.. code-block:: ipython
In [4]: s1 = pd.Series([True, False, True], index=list('ABC'))
In [5]: s2 = pd.Series([True, True, True], index=list('ABD'))
In [6]: s1 & s2
Out[6]:
A True
B False
C False
dtype: bool
New Behavior (``Series``):
.. ipython:: python
s1 = pd.Series([True, False, True], index=list('ABC'))
s2 = pd.Series([True, True, True], index=list('ABD'))
s1 & s2
.. note::
``Series`` logical operators fill ``NaN`` result with ``False``.
.. note::
To achieve the same result as previous versions (compare values based on locations ignoring ``index``), compare both ``.values``.
.. ipython:: python
s1.values & s2.values
Current Behavior (``DataFrame``, no change):
.. ipython:: python
df1 = pd.DataFrame([True, False, True], index=list('ABC'))
df2 = pd.DataFrame([True, True, True], index=list('ABD'))
df1 & df2
Flexible comparison methods
"""""""""""""""""""""""""""
``Series`` flexible comparison methods like ``eq``, ``ne``, ``le``, ``lt``, ``ge`` and ``gt`` now align both ``index``. Use these operators if you want to compare two ``Series``
which has the different ``index``.
.. ipython:: python
s1 = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
s2 = pd.Series([2, 2, 2], index=['b', 'c', 'd'])
s1.eq(s2)
s1.ge(s2)
Previously, it worked as the same as comparison operators (see above).
.. _whatsnew_0190.api.promote:
``Series`` type promotion on assignment
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A ``Series`` will now correctly promote its dtype for assignment with incompat values to the current dtype (:issue:`13234`)
.. ipython:: python
s = pd.Series()
Previous Behavior:
.. code-block:: ipython
In [2]: s["a"] = pd.Timestamp("2016-01-01")
In [3]: s["b"] = 3.0
TypeError: invalid type promotion
New Behavior:
.. ipython:: python
s["a"] = pd.Timestamp("2016-01-01")
s["b"] = 3.0
s
s.dtype
.. _whatsnew_0190.api.to_datetime_coerce:
``.to_datetime()`` changes
^^^^^^^^^^^^^^^^^^^^^^^^^^
Previously if ``.to_datetime()`` encountered mixed integers/floats and strings, but no datetimes with ``errors='coerce'`` it would convert all to ``NaT``.
Previous Behavior:
.. code-block:: ipython
In [2]: pd.to_datetime([1, 'foo'], errors='coerce')
Out[2]: DatetimeIndex(['NaT', 'NaT'], dtype='datetime64[ns]', freq=None)
This will now convert integers/floats with the default unit of ``ns``.
.. ipython:: python
pd.to_datetime([1, 'foo'], errors='coerce')
- Bug in ``pd.to_datetime()`` when passing integers or floats, and no ``unit`` and ``errors='coerce'`` (:issue:`13180`).
- Bug in ``pd.to_datetime()`` when passing invalid datatypes (e.g. bool); will now respect the ``errors`` keyword (:issue:`13176`)
- Bug in ``pd.to_datetime()`` which overflowed on ``int8``, and ``int16`` dtypes (:issue:`13451`)
- Bug in ``pd.to_datetime()`` raise ``AttributeError`` with NaN and the other string is not valid when errors='ignore' (:issue:`12424`)
- Bug in ``pd.to_datetime()`` did not cast floats correctly when ``unit`` was specified, resulting in truncated datetime (:issue:`13845`)
.. _whatsnew_0190.api.merging:
Merging changes
^^^^^^^^^^^^^^^
Merging will now preserve the dtype of the join keys (:issue:`8596`)
.. ipython:: python
df1 = pd.DataFrame({'key': [1], 'v1': [10]})
df1
df2 = pd.DataFrame({'key': [1, 2], 'v1': [20, 30]})
df2
Previous Behavior:
.. code-block:: ipython
In [5]: pd.merge(df1, df2, how='outer')
Out[5]:
key v1
0 1.0 10.0
1 1.0 20.0
2 2.0 30.0
In [6]: pd.merge(df1, df2, how='outer').dtypes
Out[6]:
key float64
v1 float64
dtype: object
New Behavior:
We are able to preserve the join keys
.. ipython:: python
pd.merge(df1, df2, how='outer')
pd.merge(df1, df2, how='outer').dtypes
Of course if you have missing values that are introduced, then the
resulting dtype will be upcast, which is unchanged from previous.
.. ipython:: python
pd.merge(df1, df2, how='outer', on='key')
pd.merge(df1, df2, how='outer', on='key').dtypes
.. _whatsnew_0190.api.describe:
``.describe()`` changes
^^^^^^^^^^^^^^^^^^^^^^^
Percentile identifiers in the index of a ``.describe()`` output will now be rounded to the least precision that keeps them distinct (:issue:`13104`)
.. ipython:: python
s = pd.Series([0, 1, 2, 3, 4])
df = pd.DataFrame([0, 1, 2, 3, 4])
Previous Behavior:
The percentiles were rounded to at most one decimal place, which could raise ``ValueError`` for a data frame if the percentiles were duplicated.
.. code-block:: ipython
In [3]: s.describe(percentiles=[0.0001, 0.0005, 0.001, 0.999, 0.9995, 0.9999])
Out[3]:
count 5.000000
mean 2.000000
std 1.581139
min 0.000000
0.0% 0.000400
0.1% 0.002000
0.1% 0.004000
50% 2.000000
99.9% 3.996000
100.0% 3.998000
100.0% 3.999600
max 4.000000
dtype: float64
In [4]: df.describe(percentiles=[0.0001, 0.0005, 0.001, 0.999, 0.9995, 0.9999])
Out[4]:
...
ValueError: cannot reindex from a duplicate axis
New Behavior:
.. ipython:: python
s.describe(percentiles=[0.0001, 0.0005, 0.001, 0.999, 0.9995, 0.9999])
df.describe(percentiles=[0.0001, 0.0005, 0.001, 0.999, 0.9995, 0.9999])
Furthermore:
- Passing duplicated ``percentiles`` will now raise a ``ValueError``.
- Bug in ``.describe()`` on a DataFrame with a mixed-dtype column index, which would previously raise a ``TypeError`` (:issue:`13288`)
.. _whatsnew_0190.api.period:
``Period`` changes
^^^^^^^^^^^^^^^^^^
``PeriodIndex`` now has ``period`` dtype
""""""""""""""""""""""""""""""""""""""""
``PeriodIndex`` now has its own ``period`` dtype. The ``period`` dtype is a
pandas extension dtype like ``category`` or :ref:`timezone aware dtype <timeseries.timezone_series>` (``datetime64[ns, tz]``). (:issue:`13941`).
As a consequence of this change, ``PeriodIndex`` no longer has an integer dtype:
Previous Behavior:
.. code-block:: ipython
In [1]: pi = pd.PeriodIndex(['2016-08-01'], freq='D')
In [2]: pi
Out[2]: PeriodIndex(['2016-08-01'], dtype='int64', freq='D')
In [3]: pd.api.types.is_integer_dtype(pi)
Out[3]: True
In [4]: pi.dtype
Out[4]: dtype('int64')
New Behavior:
.. ipython:: python
pi = pd.PeriodIndex(['2016-08-01'], freq='D')
pi
pd.api.types.is_integer_dtype(pi)
pd.api.types.is_period_dtype(pi)
pi.dtype
type(pi.dtype)
.. _whatsnew_0190.api.periodnat:
``Period('NaT')`` now returns ``pd.NaT``
""""""""""""""""""""""""""""""""""""""""
Previously, ``Period`` has its own ``Period('NaT')`` representation different from ``pd.NaT``. Now ``Period('NaT')`` has been changed to return ``pd.NaT``. (:issue:`12759`, :issue:`13582`)
Previous Behavior:
.. code-block:: ipython
In [5]: pd.Period('NaT', freq='D')
Out[5]: Period('NaT', 'D')
New Behavior:
These result in ``pd.NaT`` without providing ``freq`` option.
.. ipython:: python
pd.Period('NaT')
pd.Period(None)
To be compat with ``Period`` addition and subtraction, ``pd.NaT`` now supports addition and subtraction with ``int``. Previously it raises ``ValueError``.
Previous Behavior:
.. code-block:: ipython
In [5]: pd.NaT + 1
...
ValueError: Cannot add integral value to Timestamp without freq.
New Behavior:
.. ipython:: python
pd.NaT + 1
pd.NaT - 1
``PeriodIndex.values`` now returns array of ``Period`` object
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
``.values`` is changed to return array of ``Period`` object, rather than array
of ``int64`` (:issue:`13988`)
.. code-block:: ipython
In [6]: pi = pd.PeriodIndex(['2011-01', '2011-02'], freq='M')
In [7]: pi.values
array([492, 493])
.. ipython:: python
pi = pd.PeriodIndex(['2011-01', '2011-02'], freq='M')
pi.values
.. _whatsnew_0190.api.difference:
``Index.difference`` and ``.symmetric_difference`` changes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
``Index.difference`` and ``Index.symmetric_difference`` will now, more consistently, treat ``NaN`` values as any other values. (:issue:`13514`)
.. ipython:: python
idx1 = pd.Index([1, 2, 3, np.nan])
idx2 = pd.Index([0, 1, np.nan])
Previous Behavior:
.. code-block:: ipython
In [3]: idx1.difference(idx2)
Out[3]: Float64Index([nan, 2.0, 3.0], dtype='float64')
In [4]: idx1.symmetric_difference(idx2)
Out[4]: Float64Index([0.0, nan, 2.0, 3.0], dtype='float64')
New Behavior:
.. ipython:: python
idx1.difference(idx2)
idx1.symmetric_difference(idx2)
.. _whatsnew_0190.api.unique_index:
``Index.unique`` consistently returns ``Index``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
``Index.unique()`` now returns unique values as an
``Index`` of the appropriate ``dtype``. (:issue:`13395`)
Previously, most ``Index`` classes returned ``np.ndarray``, and ``DatetimeIndex``,
``TimedeltaIndex`` and ``PeriodIndex`` returned ``Index`` to keep metadata like timezone.
Previous Behavior:
.. code-block:: ipython
In [1]: pd.Index([1, 2, 3]).unique()
Out[1]: array([1, 2, 3])
In [2]: pd.DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03'], tz='Asia/Tokyo').unique()
Out[2]: DatetimeIndex(['2011-01-01 00:00:00+09:00', '2011-01-02 00:00:00+09:00',
'2011-01-03 00:00:00+09:00'],
dtype='datetime64[ns, Asia/Tokyo]', freq=None)
New Behavior:
.. ipython:: python
pd.Index([1, 2, 3]).unique()
pd.DatetimeIndex(['2011-01-01', '2011-01-02', '2011-01-03'], tz='Asia/Tokyo').unique()
.. _whatsnew_0190.api.multiindex:
``MultiIndex`` constructors preserve categorical dtypes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
``MultiIndex.from_arrays`` and ``MultiIndex.from_product`` will now preserve categorical dtype
in ``MultiIndex`` levels. (:issue:`13743`, :issue:`13854`)
.. ipython:: python
cat = pd.Categorical(['a', 'b'], categories=list("bac"))
lvl1 = ['foo', 'bar']
midx = pd.MultiIndex.from_arrays([cat, lvl1])
midx
Previous Behavior:
.. code-block:: ipython
In [4]: midx.levels[0]
Out[4]: Index(['b', 'a', 'c'], dtype='object')