Skip to content

Commit cd1b168

Browse files
EricCheaTomAugspurger
authored andcommitted
DOC: Add example of how to preserve order of columns with usecols. (#19746)
* Add example of how to preserve order of columns with usecols. * Encase usecols in double back ticks for consistency. Change column names from numeric to string. * Add line to separate examples.
1 parent aa59954 commit cd1b168

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

doc/source/io.rst

+8-2
Original file line numberDiff line numberDiff line change
@@ -135,8 +135,14 @@ usecols : array-like or callable, default ``None``
135135
be positional (i.e. integer indices into the document columns) or strings
136136
that correspond to column names provided either by the user in `names` or
137137
inferred from the document header row(s). For example, a valid array-like
138-
`usecols` parameter would be ``[0, 1, 2]`` or ``['foo', 'bar', 'baz']``.
139-
Element order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``.
138+
`usecols` parameter would be ``[0, 1, 2]`` or ``['foo', 'bar', 'baz']``.
139+
140+
Element order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``. To
141+
instantiate a DataFrame from ``data`` with element order preserved use
142+
``pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']]`` for columns
143+
in ``['foo', 'bar']`` order or
144+
``pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']]`` for
145+
``['bar', 'foo']`` order.
140146

141147
If callable, the callable function will be evaluated against the column names,
142148
returning names where the callable function evaluates to True:

pandas/io/parsers.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,12 @@
102102
that correspond to column names provided either by the user in `names` or
103103
inferred from the document header row(s). For example, a valid array-like
104104
`usecols` parameter would be [0, 1, 2] or ['foo', 'bar', 'baz']. Element
105-
order is ignored, so usecols=[1,0] is the same as [0,1].
105+
order is ignored, so ``usecols=[0, 1]`` is the same as ``[1, 0]``.
106+
To instantiate a DataFrame from ``data`` with element order preserved use
107+
``pd.read_csv(data, usecols=['foo', 'bar'])[['foo', 'bar']]`` for columns
108+
in ``['foo', 'bar']`` order or
109+
``pd.read_csv(data, usecols=['foo', 'bar'])[['bar', 'foo']]``
110+
for ``['bar', 'foo']`` order.
106111
107112
If callable, the callable function will be evaluated against the column
108113
names, returning names where the callable function evaluates to True. An

0 commit comments

Comments
 (0)