Skip to content

Commit e4f0045

Browse files
committed
DOC: add more examples to StringMethods on Index
1 parent 2734fff commit e4f0045

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 column names. For instance, you may have column names
42+
with leading or trailing whitespaces
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 the column of a DataFrame 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 column names as neeeded.
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)