Skip to content

Commit f5b4775

Browse files
Merge pull request #9858 from mortada/index_str_docs
DOC: add more examples to StringMethods on Index
2 parents f0ac930 + fd9d4e7 commit f5b4775

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

doc/source/text.rst

+26
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,32 @@ the equivalent (scalar) built-in string methods:
3737
idx.str.lstrip()
3838
idx.str.rstrip()
3939
40+
The string methods on Index are especially useful for cleaning up or
41+
transforming DataFrame columns. For instance, you may have columns with
42+
leading or trailing whitespace:
43+
44+
.. ipython:: python
45+
46+
df = DataFrame(randn(3, 2), columns=[' Column A ', ' Column B '],
47+
index=range(3))
48+
df
49+
50+
Since ``df.columns`` is an Index object, we can use the ``.str`` accessor
51+
52+
.. ipython:: python
53+
54+
df.columns.str.strip()
55+
df.columns.str.lower()
56+
57+
These string methods can then be used to clean up the columns as needed.
58+
Here we are removing leading and trailing whitespaces, lowercasing all names,
59+
and replacing any remaining whitespaces with underscores:
60+
61+
.. ipython:: python
62+
63+
df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_')
64+
df
65+
4066
Splitting and Replacing Strings
4167
-------------------------------
4268

0 commit comments

Comments
 (0)