forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathv0.24.0.rst
1980 lines (1459 loc) · 115 KB
/
v0.24.0.rst
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_0240:
What's New in 0.24.0 (January 25, 2019)
---------------------------------------
.. warning::
The 0.24.x series of releases will be the last to support Python 2. Future feature
releases will support Python 3 only. See :ref:`install.dropping-27` for more
details.
{{ header }}
This is a major release from 0.23.4 and includes a number of API changes, new
features, enhancements, and performance improvements along with a large number
of bug fixes.
<<<<<<< HEAD
These are the changes in pandas 0.24.0. See :ref:`release` for a full changelog
including other versions of pandas.
.. _whatsnew_0240.enhancements:
New features
~~~~~~~~~~~~
- :func:`merge` now directly allows merge between objects of type ``DataFrame`` and named ``Series``, without the need to convert the ``Series`` object into a ``DataFrame`` beforehand (:issue:`21220`)
- ``ExcelWriter`` now accepts ``mode`` as a keyword argument, enabling append to existing workbooks when using the ``openpyxl`` engine (:issue:`3441`)
- ``FrozenList`` has gained the ``.union()`` and ``.difference()`` methods. This functionality greatly simplifies groupby's that rely on explicitly excluding certain columns. See :ref:`Splitting an object into groups <groupby.split>` for more information (:issue:`15475`, :issue:`15506`).
- :func:`DataFrame.to_parquet` now accepts ``index`` as an argument, allowing
the user to override the engine's default behavior to include or omit the
dataframe's indexes from the resulting Parquet file. (:issue:`20768`)
- :meth:`DataFrame.corr` and :meth:`Series.corr` now accept a callable for generic calculation methods of correlation, e.g. histogram intersection (:issue:`22684`)
- :func:`DataFrame.to_string` now accepts ``decimal`` as an argument, allowing the user to specify which decimal separator should be used in the output. (:issue:`23614`)
- :func:`read_feather` now accepts ``columns`` as an argument, allowing the user to specify which columns should be read. (:issue:`24025`)
- :func:`DataFrame.to_html` now accepts ``render_links`` as an argument, allowing the user to generate HTML with links to any URLs that appear in the DataFrame.
See the :ref:`section on writing HTML <io.html>` in the IO docs for example usage. (:issue:`2679`)
- :func:`DataFrame.explode` to split list-like values onto individual rows. See :ref:`section on Exploding list-like column <reshaping.html>` in docs for more information (:issue:`16538`)
.. _whatsnew_0240.values_api:
Accessing the values in a Series or Index
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:attr:`Series.array` and :attr:`Index.array` have been added for extracting the array backing a
``Series`` or ``Index``. (:issue:`19954`, :issue:`23623`)
.. ipython:: python
idx = pd.period_range('2000', periods=4)
idx.array
pd.Series(idx).array
Historically, this would have been done with ``series.values``, but with
``.values`` it was unclear whether the returned value would be the actual array,
some transformation of it, or one of pandas custom arrays (like
``Categorical``). For example, with :class:`PeriodIndex`, ``.values`` generates
a new ndarray of period objects each time.
.. ipython:: python
=======
Highlights include:
>>>>>>> master
* :ref:`Optional Integer NA Support <whatsnew_0240.enhancements.intna>`
* :ref:`New APIs for accessing the array backing a Series or Index <whatsnew_0240.values_api>`
* :ref:`A new top-level method for creating arrays <whatsnew_0240.enhancements.array>`
* :ref:`Store Interval and Period data in a Series or DataFrame <whatsnew_0240.enhancements.interval>`
* :ref:`Support for joining on two MultiIndexes <whatsnew_0240.enhancements.join_with_two_multiindexes>`
Check the :ref:`API Changes <whatsnew_0240.api_breaking>` and :ref:`deprecations <whatsnew_0240.deprecations>` before updating.
These are the changes in pandas 0.24.0. See :ref:`release` for a full changelog
including other versions of pandas.
Enhancements
~~~~~~~~~~~~
.. _whatsnew_0240.enhancements.intna:
Optional Integer NA Support
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Pandas has gained the ability to hold integer dtypes with missing values. This long requested feature is enabled through the use of :ref:`extension types <extending.extension-types>`.
.. note::
IntegerArray is currently experimental. Its API or implementation may
change without warning.
We can construct a ``Series`` with the specified dtype. The dtype string ``Int64`` is a pandas ``ExtensionDtype``. Specifying a list or array using the traditional missing value
marker of ``np.nan`` will infer to integer dtype. The display of the ``Series`` will also use the ``NaN`` to indicate missing values in string outputs. (:issue:`20700`, :issue:`20747`, :issue:`22441`, :issue:`21789`, :issue:`22346`)
.. ipython:: python
s = pd.Series([1, 2, np.nan], dtype='Int64')
s
Operations on these dtypes will propagate ``NaN`` as other pandas operations.
.. ipython:: python
# arithmetic
s + 1
# comparison
s == 1
# indexing
s.iloc[1:3]
# operate with other dtypes
s + s.iloc[1:3].astype('Int8')
# coerce when needed
s + 0.01
These dtypes can operate as part of a ``DataFrame``.
.. ipython:: python
df = pd.DataFrame({'A': s, 'B': [1, 1, 3], 'C': list('aab')})
df
df.dtypes
These dtypes can be merged, reshaped, and casted.
.. ipython:: python
pd.concat([df[['A']], df[['B', 'C']]], axis=1).dtypes
df['A'].astype(float)
Reduction and groupby operations such as ``sum`` work.
.. ipython:: python
df.sum()
df.groupby('B').A.sum()
.. warning::
The Integer NA support currently uses the capitalized dtype version, e.g. ``Int8`` as compared to the traditional ``int8``. This may be changed at a future date.
See :ref:`integer_na` for more.
.. _whatsnew_0240.values_api:
Accessing the values in a Series or Index
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:attr:`Series.array` and :attr:`Index.array` have been added for extracting the array backing a
``Series`` or ``Index``. (:issue:`19954`, :issue:`23623`)
.. ipython:: python
idx = pd.period_range('2000', periods=4)
idx.array
pd.Series(idx).array
Historically, this would have been done with ``series.values``, but with
``.values`` it was unclear whether the returned value would be the actual array,
some transformation of it, or one of pandas custom arrays (like
``Categorical``). For example, with :class:`PeriodIndex`, ``.values`` generates
a new ndarray of period objects each time.
.. ipython:: python
idx.values
id(idx.values)
id(idx.values)
If you need an actual NumPy array, use :meth:`Series.to_numpy` or :meth:`Index.to_numpy`.
.. ipython:: python
idx.to_numpy()
pd.Series(idx).to_numpy()
For Series and Indexes backed by normal NumPy arrays, :attr:`Series.array` will return a
new :class:`arrays.PandasArray`, which is a thin (no-copy) wrapper around a
:class:`numpy.ndarray`. :class:`~arrays.PandasArray` isn't especially useful on its own,
but it does provide the same interface as any extension array defined in pandas or by
a third-party library.
.. ipython:: python
ser = pd.Series([1, 2, 3])
ser.array
ser.to_numpy()
We haven't removed or deprecated :attr:`Series.values` or :attr:`DataFrame.values`, but we
highly recommend and using ``.array`` or ``.to_numpy()`` instead.
See :ref:`Dtypes <basics.dtypes>` and :ref:`Attributes and Underlying Data <basics.attrs>` for more.
.. _whatsnew_0240.enhancements.array:
``pandas.array``: a new top-level method for creating arrays
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A new top-level method :func:`array` has been added for creating 1-dimensional arrays (:issue:`22860`).
This can be used to create any :ref:`extension array <extending.extension-types>`, including
extension arrays registered by :ref:`3rd party libraries <ecosystem.extensions>`.
See the :ref:`dtypes docs <basics.dtypes>` for more on extension arrays.
.. ipython:: python
pd.array([1, 2, np.nan], dtype='Int64')
pd.array(['a', 'b', 'c'], dtype='category')
Passing data for which there isn't dedicated extension type (e.g. float, integer, etc.)
will return a new :class:`arrays.PandasArray`, which is just a thin (no-copy)
wrapper around a :class:`numpy.ndarray` that satisfies the pandas extension array interface.
.. ipython:: python
pd.array([1, 2, 3])
On their own, a :class:`~arrays.PandasArray` isn't a very useful object.
But if you need write low-level code that works generically for any
:class:`~pandas.api.extensions.ExtensionArray`, :class:`~arrays.PandasArray`
satisfies that need.
Notice that by default, if no ``dtype`` is specified, the dtype of the returned
array is inferred from the data. In particular, note that the first example of
``[1, 2, np.nan]`` would have returned a floating-point array, since ``NaN``
is a float.
.. ipython:: python
pd.array([1, 2, np.nan])
.. _whatsnew_0240.enhancements.interval:
Storing Interval and Period Data in Series and DataFrame
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:class:`Interval` and :class:`Period` data may now be stored in a :class:`Series` or :class:`DataFrame`, in addition to an
:class:`IntervalIndex` and :class:`PeriodIndex` like previously (:issue:`19453`, :issue:`22862`).
.. ipython:: python
ser = pd.Series(pd.interval_range(0, 5))
ser
ser.dtype
For periods:
.. ipython:: python
pser = pd.Series(pd.period_range("2000", freq="D", periods=5))
pser
pser.dtype
Previously, these would be cast to a NumPy array with object dtype. In general,
this should result in better performance when storing an array of intervals or periods
in a :class:`Series` or column of a :class:`DataFrame`.
Use :attr:`Series.array` to extract the underlying array of intervals or periods
from the ``Series``:
.. ipython:: python
ser.array
pser.array
These return an instance of :class:`arrays.IntervalArray` or :class:`arrays.PeriodArray`,
the new extension arrays that back interval and period data.
.. warning::
For backwards compatibility, :attr:`Series.values` continues to return
a NumPy array of objects for Interval and Period data. We recommend
using :attr:`Series.array` when you need the array of data stored in the
``Series``, and :meth:`Series.to_numpy` when you know you need a NumPy array.
See :ref:`Dtypes <basics.dtypes>` and :ref:`Attributes and Underlying Data <basics.attrs>`
for more.
.. _whatsnew_0240.enhancements.join_with_two_multiindexes:
Joining with two multi-indexes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:func:`DataFrame.merge` and :func:`DataFrame.join` can now be used to join multi-indexed ``Dataframe`` instances on the overlapping index levels (:issue:`6360`)
See the :ref:`Merge, join, and concatenate
<merging.Join_with_two_multi_indexes>` documentation section.
.. ipython:: python
index_left = pd.MultiIndex.from_tuples([('K0', 'X0'), ('K0', 'X1'),
('K1', 'X2')],
names=['key', 'X'])
left = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
'B': ['B0', 'B1', 'B2']}, index=index_left)
index_right = pd.MultiIndex.from_tuples([('K0', 'Y0'), ('K1', 'Y1'),
('K2', 'Y2'), ('K2', 'Y3')],
names=['key', 'Y'])
right = pd.DataFrame({'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']}, index=index_right)
left.join(right)
For earlier versions this can be done using the following.
.. ipython:: python
pd.merge(left.reset_index(), right.reset_index(),
on=['key'], how='inner').set_index(['key', 'X', 'Y'])
.. _whatsnew_0240.enhancements.read_html:
``read_html`` Enhancements
^^^^^^^^^^^^^^^^^^^^^^^^^^
:func:`read_html` previously ignored ``colspan`` and ``rowspan`` attributes.
Now it understands them, treating them as sequences of cells with the same
value. (:issue:`17054`)
.. ipython:: python
result = pd.read_html("""
<table>
<thead>
<tr>
<th>A</th><th>B</th><th>C</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="2">1</td><td>2</td>
</tr>
</tbody>
</table>""")
*Previous Behavior*:
.. code-block:: ipython
In [13]: result
Out [13]:
[ A B C
0 1 2 NaN]
*New Behavior*:
.. ipython:: python
result
New ``Styler.pipe()`` method
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The :class:`~pandas.io.formats.style.Styler` class has gained a
:meth:`~pandas.io.formats.style.Styler.pipe` method. This provides a
convenient way to apply users' predefined styling functions, and can help reduce
"boilerplate" when using DataFrame styling functionality repeatedly within a notebook. (:issue:`23229`)
.. ipython:: python
df = pd.DataFrame({'N': [1250, 1500, 1750], 'X': [0.25, 0.35, 0.50]})
def format_and_align(styler):
return (styler.format({'N': '{:,}', 'X': '{:.1%}'})
.set_properties(**{'text-align': 'right'}))
df.style.pipe(format_and_align).set_caption('Summary of results.')
Similar methods already exist for other classes in pandas, including :meth:`DataFrame.pipe`,
:meth:`GroupBy.pipe() <pandas.core.groupby.GroupBy.pipe>`, and :meth:`Resampler.pipe() <pandas.core.resample.Resampler.pipe>`.
.. _whatsnew_0240.enhancements.rename_axis:
Renaming names in a MultiIndex
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:func:`DataFrame.rename_axis` now supports ``index`` and ``columns`` arguments
and :func:`Series.rename_axis` supports ``index`` argument (:issue:`19978`).
This change allows a dictionary to be passed so that some of the names
of a ``MultiIndex`` can be changed.
Example:
.. ipython:: python
mi = pd.MultiIndex.from_product([list('AB'), list('CD'), list('EF')],
names=['AB', 'CD', 'EF'])
df = pd.DataFrame([i for i in range(len(mi))], index=mi, columns=['N'])
df
df.rename_axis(index={'CD': 'New'})
See the :ref:`Advanced documentation on renaming<advanced.index_names>` for more details.
.. _whatsnew_0240.enhancements.other:
Other Enhancements
^^^^^^^^^^^^^^^^^^
- :func:`merge` now directly allows merge between objects of type ``DataFrame`` and named ``Series``, without the need to convert the ``Series`` object into a ``DataFrame`` beforehand (:issue:`21220`)
- ``ExcelWriter`` now accepts ``mode`` as a keyword argument, enabling append to existing workbooks when using the ``openpyxl`` engine (:issue:`3441`)
- ``FrozenList`` has gained the ``.union()`` and ``.difference()`` methods. This functionality greatly simplifies groupby's that rely on explicitly excluding certain columns. See :ref:`Splitting an object into groups <groupby.split>` for more information (:issue:`15475`, :issue:`15506`).
- :func:`DataFrame.to_parquet` now accepts ``index`` as an argument, allowing
the user to override the engine's default behavior to include or omit the
dataframe's indexes from the resulting Parquet file. (:issue:`20768`)
- :func:`read_feather` now accepts ``columns`` as an argument, allowing the user to specify which columns should be read. (:issue:`24025`)
- :meth:`DataFrame.corr` and :meth:`Series.corr` now accept a callable for generic calculation methods of correlation, e.g. histogram intersection (:issue:`22684`)
- :func:`DataFrame.to_string` now accepts ``decimal`` as an argument, allowing the user to specify which decimal separator should be used in the output. (:issue:`23614`)
- :func:`DataFrame.to_html` now accepts ``render_links`` as an argument, allowing the user to generate HTML with links to any URLs that appear in the DataFrame.
See the :ref:`section on writing HTML <io.html>` in the IO docs for example usage. (:issue:`2679`)
- :func:`pandas.read_csv` now supports pandas extension types as an argument to ``dtype``, allowing the user to use pandas extension types when reading CSVs. (:issue:`23228`)
- The :meth:`~DataFrame.shift` method now accepts `fill_value` as an argument, allowing the user to specify a value which will be used instead of NA/NaT in the empty periods. (:issue:`15486`)
- :func:`to_datetime` now supports the ``%Z`` and ``%z`` directive when passed into ``format`` (:issue:`13486`)
- :func:`Series.mode` and :func:`DataFrame.mode` now support the ``dropna`` parameter which can be used to specify whether ``NaN``/``NaT`` values should be considered (:issue:`17534`)
- :func:`DataFrame.to_csv` and :func:`Series.to_csv` now support the ``compression`` keyword when a file handle is passed. (:issue:`21227`)
- :meth:`Index.droplevel` is now implemented also for flat indexes, for compatibility with :class:`MultiIndex` (:issue:`21115`)
- :meth:`Series.droplevel` and :meth:`DataFrame.droplevel` are now implemented (:issue:`20342`)
- Added support for reading from/writing to Google Cloud Storage via the ``gcsfs`` library (:issue:`19454`, :issue:`23094`)
- :func:`DataFrame.to_gbq` and :func:`read_gbq` signature and documentation updated to
reflect changes from the `Pandas-GBQ library version 0.8.0
<https://pandas-gbq.readthedocs.io/en/latest/changelog.html#changelog-0-8-0>`__.
Adds a ``credentials`` argument, which enables the use of any kind of
`google-auth credentials
<https://google-auth.readthedocs.io/en/latest/>`__. (:issue:`21627`,
:issue:`22557`, :issue:`23662`)
- New method :meth:`HDFStore.walk` will recursively walk the group hierarchy of an HDF5 file (:issue:`10932`)
- :func:`read_html` copies cell data across ``colspan`` and ``rowspan``, and it treats all-``th`` table rows as headers if ``header`` kwarg is not given and there is no ``thead`` (:issue:`17054`)
- :meth:`Series.nlargest`, :meth:`Series.nsmallest`, :meth:`DataFrame.nlargest`, and :meth:`DataFrame.nsmallest` now accept the value ``"all"`` for the ``keep`` argument. This keeps all ties for the nth largest/smallest value (:issue:`16818`)
- :class:`IntervalIndex` has gained the :meth:`~IntervalIndex.set_closed` method to change the existing ``closed`` value (:issue:`21670`)
- :func:`~DataFrame.to_csv`, :func:`~Series.to_csv`, :func:`~DataFrame.to_json`, and :func:`~Series.to_json` now support ``compression='infer'`` to infer compression based on filename extension (:issue:`15008`).
The default compression for ``to_csv``, ``to_json``, and ``to_pickle`` methods has been updated to ``'infer'`` (:issue:`22004`).
- :meth:`DataFrame.to_sql` now supports writing ``TIMESTAMP WITH TIME ZONE`` types for supported databases. For databases that don't support timezones, datetime data will be stored as timezone unaware local timestamps. See the :ref:`io.sql_datetime_data` for implications (:issue:`9086`).
- :func:`to_timedelta` now supports iso-formated timedelta strings (:issue:`21877`)
- :class:`Series` and :class:`DataFrame` now support :class:`Iterable` objects in the constructor (:issue:`2193`)
- :class:`DatetimeIndex` has gained the :attr:`DatetimeIndex.timetz` attribute. This returns the local time with timezone information. (:issue:`21358`)
- :meth:`~Timestamp.round`, :meth:`~Timestamp.ceil`, and :meth:`~Timestamp.floor` for :class:`DatetimeIndex` and :class:`Timestamp`
now support an ``ambiguous`` argument for handling datetimes that are rounded to ambiguous times (:issue:`18946`)
and a ``nonexistent`` argument for handling datetimes that are rounded to nonexistent times. See :ref:`timeseries.timezone_nonexistent` (:issue:`22647`)
- The result of :meth:`~DataFrame.resample` is now iterable similar to ``groupby()`` (:issue:`15314`).
- :meth:`Series.resample` and :meth:`DataFrame.resample` have gained the :meth:`pandas.core.resample.Resampler.quantile` (:issue:`15023`).
- :meth:`DataFrame.resample` and :meth:`Series.resample` with a :class:`PeriodIndex` will now respect the ``base`` argument in the same fashion as with a :class:`DatetimeIndex`. (:issue:`23882`)
- :meth:`pandas.api.types.is_list_like` has gained a keyword ``allow_sets`` which is ``True`` by default; if ``False``,
all instances of ``set`` will not be considered "list-like" anymore (:issue:`23061`)
- :meth:`Index.to_frame` now supports overriding column name(s) (:issue:`22580`).
- :meth:`Categorical.from_codes` now can take a ``dtype`` parameter as an alternative to passing ``categories`` and ``ordered`` (:issue:`24398`).
- New attribute ``__git_version__`` will return git commit sha of current build (:issue:`21295`).
- Compatibility with Matplotlib 3.0 (:issue:`22790`).
- Added :meth:`Interval.overlaps`, :meth:`arrays.IntervalArray.overlaps`, and :meth:`IntervalIndex.overlaps` for determining overlaps between interval-like objects (:issue:`21998`)
- :func:`read_fwf` now accepts keyword ``infer_nrows`` (:issue:`15138`).
- :func:`~DataFrame.to_parquet` now supports writing a ``DataFrame`` as a directory of parquet files partitioned by a subset of the columns when ``engine = 'pyarrow'`` (:issue:`23283`)
- :meth:`Timestamp.tz_localize`, :meth:`DatetimeIndex.tz_localize`, and :meth:`Series.tz_localize` have gained the ``nonexistent`` argument for alternative handling of nonexistent times. See :ref:`timeseries.timezone_nonexistent` (:issue:`8917`, :issue:`24466`)
- :meth:`Index.difference`, :meth:`Index.intersection`, :meth:`Index.union`, and :meth:`Index.symmetric_difference` now have an optional ``sort`` parameter to control whether the results should be sorted if possible (:issue:`17839`, :issue:`24471`)
- :meth:`read_excel()` now accepts ``usecols`` as a list of column names or callable (:issue:`18273`)
- :meth:`MultiIndex.to_flat_index` has been added to flatten multiple levels into a single-level :class:`Index` object.
- :meth:`DataFrame.to_stata` and :class:`pandas.io.stata.StataWriter117` can write mixed sting columns to Stata strl format (:issue:`23633`)
- :meth:`DataFrame.between_time` and :meth:`DataFrame.at_time` have gained the ``axis`` parameter (:issue:`8839`)
- :meth:`DataFrame.to_records` now accepts ``index_dtypes`` and ``column_dtypes`` parameters to allow different data types in stored column and index records (:issue:`18146`)
- :class:`IntervalIndex` has gained the :attr:`~IntervalIndex.is_overlapping` attribute to indicate if the ``IntervalIndex`` contains any overlapping intervals (:issue:`23309`)
- :func:`pandas.DataFrame.to_sql` has gained the ``method`` argument to control SQL insertion clause. See the :ref:`insertion method <io.sql.method>` section in the documentation. (:issue:`8953`)
- :meth:`DataFrame.corrwith` now supports Spearman's rank correlation, Kendall's tau as well as callable correlation methods. (:issue:`21925`)
- :meth:`DataFrame.to_json`, :meth:`DataFrame.to_csv`, :meth:`DataFrame.to_pickle`, and other export methods now support tilde(~) in path argument. (:issue:`23473`)
.. _whatsnew_0240.api_breaking:
Backwards incompatible API changes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Pandas 0.24.0 includes a number of API breaking changes.
.. _whatsnew_0240.api_breaking.deps:
Increased minimum versions for dependencies
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
We have updated our minimum supported versions of dependencies (:issue:`21242`, :issue:`18742`, :issue:`23774`, :issue:`24767`).
If installed, we now require:
+-----------------+-----------------+----------+
| Package | Minimum Version | Required |
+=================+=================+==========+
| numpy | 1.12.0 | X |
+-----------------+-----------------+----------+
| bottleneck | 1.2.0 | |
+-----------------+-----------------+----------+
| fastparquet | 0.2.1 | |
+-----------------+-----------------+----------+
| matplotlib | 2.0.0 | |
+-----------------+-----------------+----------+
| numexpr | 2.6.1 | |
+-----------------+-----------------+----------+
| pandas-gbq | 0.8.0 | |
+-----------------+-----------------+----------+
| pyarrow | 0.9.0 | |
+-----------------+-----------------+----------+
| pytables | 3.4.2 | |
+-----------------+-----------------+----------+
| scipy | 0.18.1 | |
+-----------------+-----------------+----------+
| xlrd | 1.0.0 | |
+-----------------+-----------------+----------+
| pytest (dev) | 3.6 | |
+-----------------+-----------------+----------+
Additionally we no longer depend on ``feather-format`` for feather based storage
and replaced it with references to ``pyarrow`` (:issue:`21639` and :issue:`23053`).
.. _whatsnew_0240.api_breaking.csv_line_terminator:
`os.linesep` is used for ``line_terminator`` of ``DataFrame.to_csv``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:func:`DataFrame.to_csv` now uses :func:`os.linesep` rather than ``'\n'``
for the default line terminator (:issue:`20353`).
This change only affects when running on Windows, where ``'\r\n'`` was used for line terminator
even when ``'\n'`` was passed in ``line_terminator``.
*Previous Behavior* on Windows:
.. code-block:: ipython
In [1]: data = pd.DataFrame({"string_with_lf": ["a\nbc"],
...: "string_with_crlf": ["a\r\nbc"]})
In [2]: # When passing file PATH to to_csv,
...: # line_terminator does not work, and csv is saved with '\r\n'.
...: # Also, this converts all '\n's in the data to '\r\n'.
...: data.to_csv("test.csv", index=False, line_terminator='\n')
In [3]: with open("test.csv", mode='rb') as f:
...: print(f.read())
Out[3]: b'string_with_lf,string_with_crlf\r\n"a\r\nbc","a\r\r\nbc"\r\n'
In [4]: # When passing file OBJECT with newline option to
...: # to_csv, line_terminator works.
...: with open("test2.csv", mode='w', newline='\n') as f:
...: data.to_csv(f, index=False, line_terminator='\n')
In [5]: with open("test2.csv", mode='rb') as f:
...: print(f.read())
Out[5]: b'string_with_lf,string_with_crlf\n"a\nbc","a\r\nbc"\n'
*New Behavior* on Windows:
Passing ``line_terminator`` explicitly, set thes ``line terminator`` to that character.
.. code-block:: ipython
In [1]: data = pd.DataFrame({"string_with_lf": ["a\nbc"],
...: "string_with_crlf": ["a\r\nbc"]})
In [2]: data.to_csv("test.csv", index=False, line_terminator='\n')
In [3]: with open("test.csv", mode='rb') as f:
...: print(f.read())
Out[3]: b'string_with_lf,string_with_crlf\n"a\nbc","a\r\nbc"\n'
On Windows, the value of ``os.linesep`` is ``'\r\n'``, so if ``line_terminator`` is not
set, ``'\r\n'`` is used for line terminator.
.. code-block:: ipython
In [1]: data = pd.DataFrame({"string_with_lf": ["a\nbc"],
...: "string_with_crlf": ["a\r\nbc"]})
In [2]: data.to_csv("test.csv", index=False)
In [3]: with open("test.csv", mode='rb') as f:
...: print(f.read())
Out[3]: b'string_with_lf,string_with_crlf\r\n"a\nbc","a\r\nbc"\r\n'
For file objects, specifying ``newline`` is not sufficient to set the line terminator.
You must pass in the ``line_terminator`` explicitly, even in this case.
.. code-block:: ipython
In [1]: data = pd.DataFrame({"string_with_lf": ["a\nbc"],
...: "string_with_crlf": ["a\r\nbc"]})
In [2]: with open("test2.csv", mode='w', newline='\n') as f:
...: data.to_csv(f, index=False)
In [3]: with open("test2.csv", mode='rb') as f:
...: print(f.read())
Out[3]: b'string_with_lf,string_with_crlf\r\n"a\nbc","a\r\nbc"\r\n'
.. _whatsnew_0240.bug_fixes.nan_with_str_dtype:
Proper handling of `np.NaN` in a string data-typed column with the Python engine
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
There was bug in :func:`read_excel` and :func:`read_csv` with the Python
engine, where missing values turned to ``'nan'`` with ``dtype=str`` and
``na_filter=True``. Now, these missing values are converted to the string
missing indicator, ``np.nan``. (:issue:`20377`)
.. ipython:: python
:suppress:
from io import StringIO
*Previous Behavior*:
.. code-block:: ipython
In [5]: data = 'a,b,c\n1,,3\n4,5,6'
In [6]: df = pd.read_csv(StringIO(data), engine='python', dtype=str, na_filter=True)
In [7]: df.loc[0, 'b']
Out[7]:
'nan'
*New Behavior*:
.. ipython:: python
data = 'a,b,c\n1,,3\n4,5,6'
df = pd.read_csv(StringIO(data), engine='python', dtype=str, na_filter=True)
df.loc[0, 'b']
Notice how we now instead output ``np.nan`` itself instead of a stringified form of it.
.. _whatsnew_0240.api.timezone_offset_parsing:
Parsing Datetime Strings with Timezone Offsets
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Previously, parsing datetime strings with UTC offsets with :func:`to_datetime`
or :class:`DatetimeIndex` would automatically convert the datetime to UTC
without timezone localization. This is inconsistent from parsing the same
datetime string with :class:`Timestamp` which would preserve the UTC
offset in the ``tz`` attribute. Now, :func:`to_datetime` preserves the UTC
offset in the ``tz`` attribute when all the datetime strings have the same
UTC offset (:issue:`17697`, :issue:`11736`, :issue:`22457`)
*Previous Behavior*:
.. code-block:: ipython
In [2]: pd.to_datetime("2015-11-18 15:30:00+05:30")
Out[2]: Timestamp('2015-11-18 10:00:00')
In [3]: pd.Timestamp("2015-11-18 15:30:00+05:30")
Out[3]: Timestamp('2015-11-18 15:30:00+0530', tz='pytz.FixedOffset(330)')
# Different UTC offsets would automatically convert the datetimes to UTC (without a UTC timezone)
In [4]: pd.to_datetime(["2015-11-18 15:30:00+05:30", "2015-11-18 16:30:00+06:30"])
Out[4]: DatetimeIndex(['2015-11-18 10:00:00', '2015-11-18 10:00:00'], dtype='datetime64[ns]', freq=None)
*New Behavior*:
.. ipython:: python
pd.to_datetime("2015-11-18 15:30:00+05:30")
pd.Timestamp("2015-11-18 15:30:00+05:30")
Parsing datetime strings with the same UTC offset will preserve the UTC offset in the ``tz``
.. ipython:: python
pd.to_datetime(["2015-11-18 15:30:00+05:30"] * 2)
Parsing datetime strings with different UTC offsets will now create an Index of
``datetime.datetime`` objects with different UTC offsets
.. ipython:: python
idx = pd.to_datetime(["2015-11-18 15:30:00+05:30",
"2015-11-18 16:30:00+06:30"])
idx
idx[0]
idx[1]
Passing ``utc=True`` will mimic the previous behavior but will correctly indicate
that the dates have been converted to UTC
.. ipython:: python
pd.to_datetime(["2015-11-18 15:30:00+05:30",
"2015-11-18 16:30:00+06:30"], utc=True)
.. _whatsnew_0240.api_breaking.read_csv_mixed_tz:
Parsing mixed-timezones with :func:`read_csv`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:func:`read_csv` no longer silently converts mixed-timezone columns to UTC (:issue:`24987`).
*Previous Behavior*
.. code-block:: python
>>> import io
>>> content = """\
... a
... 2000-01-01T00:00:00+05:00
... 2000-01-01T00:00:00+06:00"""
>>> df = pd.read_csv(io.StringIO(content), parse_dates=['a'])
>>> df.a
0 1999-12-31 19:00:00
1 1999-12-31 18:00:00
Name: a, dtype: datetime64[ns]
*New Behavior*
.. ipython:: python
import io
content = """\
a
2000-01-01T00:00:00+05:00
2000-01-01T00:00:00+06:00"""
df = pd.read_csv(io.StringIO(content), parse_dates=['a'])
df.a
As can be seen, the ``dtype`` is object; each value in the column is a string.
To convert the strings to an array of datetimes, the ``date_parser`` argument
.. ipython:: python
df = pd.read_csv(io.StringIO(content), parse_dates=['a'],
date_parser=lambda col: pd.to_datetime(col, utc=True))
df.a
See :ref:`whatsnew_0240.api.timezone_offset_parsing` for more.
.. _whatsnew_0240.api_breaking.period_end_time:
Time values in ``dt.end_time`` and ``to_timestamp(how='end')``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The time values in :class:`Period` and :class:`PeriodIndex` objects are now set
to '23:59:59.999999999' when calling :attr:`Series.dt.end_time`, :attr:`Period.end_time`,
:attr:`PeriodIndex.end_time`, :func:`Period.to_timestamp()` with ``how='end'``,
or :func:`PeriodIndex.to_timestamp()` with ``how='end'`` (:issue:`17157`)
*Previous Behavior*:
.. code-block:: ipython
In [2]: p = pd.Period('2017-01-01', 'D')
In [3]: pi = pd.PeriodIndex([p])
In [4]: pd.Series(pi).dt.end_time[0]
Out[4]: Timestamp(2017-01-01 00:00:00)
In [5]: p.end_time
Out[5]: Timestamp(2017-01-01 23:59:59.999999999)
*New Behavior*:
Calling :attr:`Series.dt.end_time` will now result in a time of '23:59:59.999999999' as
is the case with :attr:`Period.end_time`, for example
.. ipython:: python
p = pd.Period('2017-01-01', 'D')
pi = pd.PeriodIndex([p])
pd.Series(pi).dt.end_time[0]
p.end_time
.. _whatsnew_0240.api_breaking.datetime_unique:
Series.unique for Timezone-Aware Data
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The return type of :meth:`Series.unique` for datetime with timezone values has changed
from an :class:`numpy.ndarray` of :class:`Timestamp` objects to a :class:`arrays.DatetimeArray` (:issue:`24024`).
.. ipython:: python
ser = pd.Series([pd.Timestamp('2000', tz='UTC'),
pd.Timestamp('2000', tz='UTC')])
*Previous Behavior*:
.. code-block:: ipython
In [3]: ser.unique()
Out[3]: array([Timestamp('2000-01-01 00:00:00+0000', tz='UTC')], dtype=object)
*New Behavior*:
.. ipython:: python
ser.unique()
.. _whatsnew_0240.api_breaking.sparse_values:
Sparse Data Structure Refactor
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
``SparseArray``, the array backing ``SparseSeries`` and the columns in a ``SparseDataFrame``,
is now an extension array (:issue:`21978`, :issue:`19056`, :issue:`22835`).
To conform to this interface and for consistency with the rest of pandas, some API breaking
changes were made:
- ``SparseArray`` is no longer a subclass of :class:`numpy.ndarray`. To convert a ``SparseArray`` to a NumPy array, use :func:`numpy.asarray`.
- ``SparseArray.dtype`` and ``SparseSeries.dtype`` are now instances of :class:`SparseDtype`, rather than ``np.dtype``. Access the underlying dtype with ``SparseDtype.subtype``.
- ``numpy.asarray(sparse_array)`` now returns a dense array with all the values, not just the non-fill-value values (:issue:`14167`)
- ``SparseArray.take`` now matches the API of :meth:`pandas.api.extensions.ExtensionArray.take` (:issue:`19506`):
* The default value of ``allow_fill`` has changed from ``False`` to ``True``.
* The ``out`` and ``mode`` parameters are now longer accepted (previously, this raised if they were specified).
* Passing a scalar for ``indices`` is no longer allowed.
- The result of :func:`concat` with a mix of sparse and dense Series is a Series with sparse values, rather than a ``SparseSeries``.
- ``SparseDataFrame.combine`` and ``DataFrame.combine_first`` no longer supports combining a sparse column with a dense column while preserving the sparse subtype. The result will be an object-dtype SparseArray.
- Setting :attr:`SparseArray.fill_value` to a fill value with a different dtype is now allowed.
- ``DataFrame[column]`` is now a :class:`Series` with sparse values, rather than a :class:`SparseSeries`, when slicing a single column with sparse values (:issue:`23559`).
- The result of :meth:`Series.where` is now a ``Series`` with sparse values, like with other extension arrays (:issue:`24077`)
Some new warnings are issued for operations that require or are likely to materialize a large dense array:
- A :class:`errors.PerformanceWarning` is issued when using fillna with a ``method``, as a dense array is constructed to create the filled array. Filling with a ``value`` is the efficient way to fill a sparse array.
- A :class:`errors.PerformanceWarning` is now issued when concatenating sparse Series with differing fill values. The fill value from the first sparse array continues to be used.
In addition to these API breaking changes, many :ref:`Performance Improvements and Bug Fixes have been made <whatsnew_0240.bug_fixes.sparse>`.
Finally, a ``Series.sparse`` accessor was added to provide sparse-specific methods like :meth:`Series.sparse.from_coo`.
.. ipython:: python
s = pd.Series([0, 0, 1, 1, 1], dtype='Sparse[int]')
s.sparse.density
.. _whatsnew_0240.api_breaking.get_dummies:
:meth:`get_dummies` always returns a DataFrame
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Previously, when ``sparse=True`` was passed to :func:`get_dummies`, the return value could be either
a :class:`DataFrame` or a :class:`SparseDataFrame`, depending on whether all or a just a subset
of the columns were dummy-encoded. Now, a :class:`DataFrame` is always returned (:issue:`24284`).
*Previous Behavior*
The first :func:`get_dummies` returns a :class:`DataFrame` because the column ``A``
is not dummy encoded. When just ``["B", "C"]`` are passed to ``get_dummies``,
then all the columns are dummy-encoded, and a :class:`SparseDataFrame` was returned.
.. code-block:: ipython
In [2]: df = pd.DataFrame({"A": [1, 2], "B": ['a', 'b'], "C": ['a', 'a']})
In [3]: type(pd.get_dummies(df, sparse=True))
Out[3]: pandas.core.frame.DataFrame
In [4]: type(pd.get_dummies(df[['B', 'C']], sparse=True))
Out[4]: pandas.core.sparse.frame.SparseDataFrame
.. ipython:: python
:suppress:
df = pd.DataFrame({"A": [1, 2], "B": ['a', 'b'], "C": ['a', 'a']})
*New Behavior*
Now, the return type is consistently a :class:`DataFrame`.
.. ipython:: python
type(pd.get_dummies(df, sparse=True))
type(pd.get_dummies(df[['B', 'C']], sparse=True))
.. note::
There's no difference in memory usage between a :class:`SparseDataFrame`
and a :class:`DataFrame` with sparse values. The memory usage will
be the same as in the previous version of pandas.
.. _whatsnew_0240.api_breaking.frame_to_dict_index_orient:
Raise ValueError in ``DataFrame.to_dict(orient='index')``
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Bug in :func:`DataFrame.to_dict` raises ``ValueError`` when used with
``orient='index'`` and a non-unique index instead of losing data (:issue:`22801`)
.. ipython:: python
:okexcept:
df = pd.DataFrame({'a': [1, 2], 'b': [0.5, 0.75]}, index=['A', 'A'])
df
df.to_dict(orient='index')
.. _whatsnew_0240.api.datetimelike.normalize:
Tick DateOffset Normalize Restrictions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Creating a ``Tick`` object (:class:`Day`, :class:`Hour`, :class:`Minute`,
:class:`Second`, :class:`Milli`, :class:`Micro`, :class:`Nano`) with
``normalize=True`` is no longer supported. This prevents unexpected behavior
where addition could fail to be monotone or associative. (:issue:`21427`)
*Previous Behavior*:
.. code-block:: ipython
In [2]: ts = pd.Timestamp('2018-06-11 18:01:14')
In [3]: ts
Out[3]: Timestamp('2018-06-11 18:01:14')
In [4]: tic = pd.offsets.Hour(n=2, normalize=True)
...:
In [5]: tic
Out[5]: <2 * Hours>
In [6]: ts + tic
Out[6]: Timestamp('2018-06-11 00:00:00')
In [7]: ts + tic + tic + tic == ts + (tic + tic + tic)
Out[7]: False
*New Behavior*:
.. ipython:: python
ts = pd.Timestamp('2018-06-11 18:01:14')
tic = pd.offsets.Hour(n=2)
ts + tic + tic + tic == ts + (tic + tic + tic)
.. _whatsnew_0240.api.datetimelike:
.. _whatsnew_0240.api.period_subtraction:
Period Subtraction
^^^^^^^^^^^^^^^^^^
Subtraction of a ``Period`` from another ``Period`` will give a ``DateOffset``.
instead of an integer (:issue:`21314`)
*Previous Behavior*:
.. code-block:: ipython
In [2]: june = pd.Period('June 2018')
In [3]: april = pd.Period('April 2018')
In [4]: june - april
Out [4]: 2
*New Behavior*:
.. ipython:: python
june = pd.Period('June 2018')
april = pd.Period('April 2018')
june - april
Similarly, subtraction of a ``Period`` from a ``PeriodIndex`` will now return
an ``Index`` of ``DateOffset`` objects instead of an ``Int64Index``
*Previous Behavior*:
.. code-block:: ipython
In [2]: pi = pd.period_range('June 2018', freq='M', periods=3)
In [3]: pi - pi[0]
Out[3]: Int64Index([0, 1, 2], dtype='int64')
*New Behavior*:
.. ipython:: python
pi = pd.period_range('June 2018', freq='M', periods=3)
pi - pi[0]
.. _whatsnew_0240.api.timedelta64_subtract_nan:
Addition/Subtraction of ``NaN`` from :class:`DataFrame`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^