We recommend using StringDtype to store text data.
Prior to pandas 1.0, object dtype was the only option. This was unfortunate
for many reasons:
You can accidentally store a mixture of strings and non-strings in an
dtype array. It’s better to have a dedicated dtype.
object
object dtype breaks dtype-specific operations like DataFrame.select_dtypes().
There isn’t a clear way to select just text while excluding non-text
but still object-dtype columns.
When reading code, the contents of an object dtype array is less clear
than 'string'.
Currently, the performance of object dtype arrays of strings and
arrays.StringArray are about the same. We expect future enhancements
to significantly increase the performance and lower the memory overhead of
StringArray.
For backwards-compatibility, object dtype remains the default type we
infer a list of strings to
In [1]: pd.Series(["a","b","c"])Out[1]: 0 a1 b2 cdtype: object
To explicitly request string dtype, specify the dtype
These are places where the behavior of StringDtype objects differ from
object dtype
For StringDtype, string accessor methods
that return numeric output will always return a nullable integer dtype,
rather than either int or float dtype, depending on the presence of NA values.
Methods returning boolean output will return a nullable boolean dtype.
Some string methods, like Series.str.decode() are not available
on StringArray because StringArray only holds strings, not
bytes.
In comparison operations, arrays.StringArray and Series backed
by a StringArray will return an object with BooleanDtype,
rather than a bool dtype object. Missing values in a
will propagate in comparison operations, rather than always comparing
unequal like .
Everything else that follows in the rest of this document applies equally to
string and object dtype.
String methods
Series and Index are equipped with a set of string processing methods
that make it easy to operate on each element of the array. Perhaps most
importantly, these methods exclude missing/NA values automatically. These are
accessed via the str attribute and generally have names matching
the equivalent (scalar) built-in string methods:
The string methods on Index are especially useful for cleaning up or
transforming DataFrame columns. For instance, you may have columns with
leading or trailing whitespace:
In [32]: df=pd.DataFrame( ....: np.random.randn(3,2),columns=[" Column A "," Column B "],index=range(3) ....: ) ....: In [33]: dfOut[33]:
Since df.columns is an Index object, we can use the .str accessor
In [34]: df.columns.str.strip()Out[34]: Index(['Column A', 'Column B'], dtype='object')In [35]: df.columns.str.lower()Out[35]: Index([' column a ', ' column b '], dtype='object')
These string methods can then be used to clean up the columns as needed.
Here we are removing leading and trailing whitespaces, lower casing all names,
and replacing any remaining whitespaces with underscores:
If you want literal replacement of a string (equivalent to str.replace()), you
can set the optional regex parameter to False, rather than escaping each
character. In this case both pat and repl must be strings:
In [51]: dollars=pd.Series(["12","-$10","$10,000"],dtype="string")# These lines are equivalentIn [52]: dollars.str.replace(r"-\$","-",regex=True)Out[52]: 0 121 -102 $10,000
The replace method can also take a callable as replacement. It is called
on every pat using re.sub(). The callable should expect one
positional argument (a regex object) and return a string.
# Reverse every lowercase alphabetic wordIn [54]: pat=r"[a-z]+"In [55]: defrepl(m): ....: returnm.group(0)[::-1] ....: In [56]: pd.Series(["foo 123","bar baz",np.nan
The replace method also accepts a compiled regular expression object
from re.compile() as a pattern. All flags should be included in the
compiled regular expression object.
In [60]: importreIn [61]: regex_pat=re.compile(r"^.a|dog",flags=re.IGNORECASE)In [62]: s3.str.replace(regex_pat,"XX-XX ",regex=True)Out[62]: 0 A1 B
Including a flags argument when calling replace with a compiled
regular expression object will raise a ValueError.
In [63]: s3.str.replace(regex_pat,'XX-XX ',flags=re.IGNORECASE)---------------------------------------------------------------------------ValueError: case and flags cannot be set when pat is a compiled regex
There are several ways to concatenate a Series or Index, either with itself or others, all based on cat(),
resp. Index.str.cat.
Concatenating a single Series into a string
The content of a Series (or Index) can be concatenated:
In [68]: s=pd.Series(["a","b","c","d"],dtype="string")In [69]: s.str.cat(sep=",")Out[69]: 'a,b,c,d'
If not specified, the keyword sep for the separator defaults to the empty string, sep='':
In [70]: s.str.cat()Out[70]: 'abcd'
By default, missing values are ignored. Using na_rep, they can be given a representation:
In [71]: t=pd.Series(["a","b",np.nan,"d"],dtype="string")In [72]: t.str.cat(sep=",")Out[72]: 'a,b,d'In [73]: t.
Concatenating a Series and something list-like into a Series
The first argument to cat() can be a list-like object, provided that it matches the length of the calling Series (or Index).
In [74]: s.str.cat(["A","B","C","D"])Out[74]: 0 aA1 bB
Concatenating a Series and something array-like into a Series
The parameter others can also be two-dimensional. In this case, the number or rows must match the lengths of the calling Series (or Index).
In [77]: d=pd.concat([t,s],axis=1)In [78]: sOut[78]: 0 a1 b
Concatenating a Series and an indexed object into a Series, with alignment
For concatenation with a Series or DataFrame, it is possible to align the indexes before concatenation by setting
the join-keyword.
In [81]: u=pd.Series(["b","d","a","c"],index=[1,3
Concatenating a Series and many objects into a Series
Several array-like items (specifically: Series, Index, and 1-dimensional variants of np.ndarray)
can be combined in a list-like container (including iterators, dict-views, etc.).
The extract method accepts a regular expression with at least one
capture group.
Extracting a regular expression with more than one group returns a
DataFrame with one column per group.
In [106]: pd.Series( .....: ["a1","b2","c3"], .....: dtype="string", .....: ).str.extract(r"([ab])(\d)",expand=False) .....: Out[106]: 0 10 a 11 b 22 <NA> <NA>
Elements that do not match return a row filled with NaN. Thus, a
Series of messy strings can be “converted” into a like-indexed Series
or DataFrame of cleaned-up or more useful strings, without
necessitating get() to access tuples or re.match objects. The
dtype of the result is always object, even if no match is found and
the result only contains NaN.
Named groups like
In [107]: pd.Series(["a1","b2","c3"],dtype="string").str.extract( .....: r"(?P<letter>[ab])(?P<digit>\d)",expand=False .....: ) .....: Out[107]: letter digit0 a 11 b 22 <NA> <NA>
can also be used. Note that any capture group names in the regular
expression will be used for column names; otherwise capture group
numbers will be used.
Extracting a regular expression with one group returns a DataFrame
with one column if expand=True.
In [109]: pd.Series(["a1","b2","c3"],dtype="string").str.extract(r"[ab](\d)",expand=True)Out[109]: 00 11 22 <NA>
It returns a Series if expand=False.
In [110]: pd.Series(["a1","b2","c3"],dtype="string").str.extract(r"[ab](\d)",expand=False)Out[110]: 0 11 22 <NA>dtype: string
Calling on an Index with a regex with exactly one capture group
returns a DataFrame with one column if expand=True.
In [114]: s.index.str.extract("(?P<letter>[a-zA-Z])",expand=False)Out[114]: Index(['A', 'B', 'C'], dtype='object', name='letter')
Calling on an Index with a regex with more than one capture group
returns a DataFrame if expand=True.
In [115]: s.index.str.extract("(?P<letter>[a-zA-Z])([0-9]+)",expand=True)Out[115]: letter 10 A 111 B 222 C 33
It raises ValueError if expand=False.
In [116]: s.index.str.extract("(?P<letter>[a-zA-Z])([0-9]+)",expand=False)---------------------------------------------------------------------------ValueErrorTraceback (most recent call last)
CellIn[116],line1----> 1s.index.str.extract("(?P<letter>[a-zA-Z])([0-9]+)"
in
in
: only one regex group is supported with Index
The table below summarizes the behavior of extract(expand=False)
(input subject in first column, number of groups in regex in
first row)
1 group
>1 group
Index
Index
ValueError
Series
Series
DataFrame
Extract all matches in each subject (extractall)
Unlike extract (which returns only the first match),
In [117]: s=pd.Series(["a1a2","b1","c1"],index=["A","B","C"],dtype="string")In [118]: s
Testing for strings that match or contain a pattern
Please note that a Series of type category with string .categories has
some limitations in comparison to Series of type string (e.g. you can’t add strings to
each other: s+""+s won’t work if s is a Series of type category). Also,
.str methods which operate on elements of type list are not available on such a
Series.
1 d
2 <NA>
3 g
dtype: object
....:
In [46]:
s3
Out[46]:
0 A
1 B
2 C
3 Aaba
4 Baca
5
6 <NA>
7 CABA
8 dog
9 cat
dtype: string
In [47]:
s3
.
str
.
replace
(
"^.a|dog"
,
"XX-XX "
,
case
=
False
,
regex
=
True
)
Out[47]:
0 A
1 B
2 C
3 XX-XX ba
4 XX-XX ca
5
6 <NA>
7 XX-XX BA
8 XX-XX
9 XX-XX t
dtype: string
replace
(
"."
,
"a"
,
regex
=
True
)
Out[50]:
0 aaa
1 a
2 a
3 <NA>
4
dtype: string
dtype: string
In [53]:
dollars
.
str
.
replace
(
"-$"
,
"-"
,
regex
=
False
)
Out[53]:
0 12
1 -10
2 $10,000
dtype: string
],
dtype
=
"string"
)
.
str
.
replace
(
....:
pat
,
repl
,
regex
=
True
....:
)
....:
Out[56]:
0 oof 123
1 rab zab
2 <NA>
dtype: string
# Using regex groups
In [57]:
pat
=
r
"(?P<one>\w+) (?P<two>\w+) (?P<three>\w+)"
In [58]:
def
repl
(
m
):
....:
return
m
.
group
(
"two"
)
.
swapcase
()
....:
In [59]:
pd
.
Series
([
"Foo Bar Baz"
,
np
.
nan
],
dtype
=
"string"
)
.
str
.
replace
(
....:
pat
,
repl
,
regex
=
True
....:
)
....:
Out[59]:
0 bAR
1 <NA>
dtype: string
2 C
3 XX-XX ba
4 XX-XX ca
5
6 <NA>
7 XX-XX BA
8 XX-XX
9 XX-XX t
dtype: string
,
"no_suffix"
])
In [67]:
s
.
str
.
removesuffix
(
"_str"
)
Out[67]:
0 foo
1 bar
2 no_suffix
dtype: object
str
.
cat
(
sep
=
","
,
na_rep
=
"-"
)
Out[73]:
'a,b,-,d'
2 cC
3 dD
dtype: string
Missing values on either side will result in missing values in the result as well, unlessna_rep is specified:
The usual options are available for join (one of 'left','outer','inner','right').
In particular, alignment also means that the different lengths do not need to coincide anymore.
In [86]: v=pd.Series(["z","a","b","d","e"],index=[-1,0,1,3,4],dtype="string")In [87]: sOut[87]: 0 a1 b2 c3 ddtype: stringIn [88]: vOut[88]: -1 z 0 a 1 b 3 d 4 edtype: stringIn [89]: s.str.cat(v,join="left",na_rep="-")Out[89]: 0 aa1 bb2 c-3 dddtype: stringIn [90]: s.str.cat(v,join="outer",na_rep="-")Out[90]: -1 -z 0 aa 1 bb 2 c- 3 dd 4 -edtype: string
The same alignment can be used when others is a DataFrame:
In [91]: f=d.loc[[3,2,1,0],:]In [92]: sOut[92]: 0 a1 b2 c3 ddtype: stringIn [93]: fOut[93]: 0 13 d d2 <NA> c1 b b0 a aIn [94]: s.str.cat(f,join="left",na_rep="-")Out[94]: 0 aaa1 bbb2 c-c3 ddddtype: string
In [97]:
s
.
str
.
cat
([
u
,
u
.
to_numpy
()],
join
=
"left"
)
Out[97]:
0 aab
1 bbd
2 cca
3 ddc
dtype: string
All elements without an index (e.g. np.ndarray) within the passed list-like must match in length to the calling Series (or Index),
but Series and Index may have arbitrary length (as long as alignment is not disabled with join=None):
In [98]: vOut[98]: -1 z 0 a 1 b 3 d 4 edtype: stringIn [99]: s.str.cat([v,u,u.to_numpy()],join="outer",na_rep="-")Out[99]: -1 -z--0 aaab1 bbbd2 c-ca3 dddc4 -e--dtype: string
If using join='right' on a list-like of others that contains different indexes,
the union of these indexes will be used as the basis for the final concatenation:
the extractall method returns every match. The result of
extractall is always a DataFrame with a MultiIndex on its
rows. The last level of the MultiIndex is named match and
indicates the order in the subject.
In [121]: s.str.extractall(two_groups)Out[121]: letter digit match A 0 a 1 1 a 2B 0 b 1C 0 c 1
When each subject string in the Series has exactly one match,
In [122]: s=pd.Series(["a3","b3","c2"],dtype="string")In [123]: sOut[123]: 0 a31 b32 c2dtype: string
then extractall(pat).xs(0,level='match') gives the same result as
extract(pat).
In [124]: extract_result=s.str.extract(two_groups,expand=True)In [125]: extract_resultOut[125]: letter digit0 a 31 b 32 c 2In [126]: extractall_result=s.str.extractall(two_groups)In [127]: extractall_resultOut[127]: letter digit match 0 0 a 31 0 b 32 0 c 2In [128]: extractall_result.xs(0,level="match")Out[128]: letter digit0 a 31 b 32 c 2
Index also supports .str.extractall. It returns a DataFrame which has the
same result as a Series.str.extractall with a default index (starts from 0).
In [129]: pd.Index(["a1a2","b1","c1"]).str.extractall(two_groups)Out[129]: letter digit match 0 0 a 1 1 a 21 0 b 12 0 c 1In [130]: pd.Series(["a1a2","b1","c1"],dtype="string").str.extractall(two_groups)Out[130]: letter digit match 0 0 a 1 1 a 21 0 b 12 0 c 1