pandas.Series.str.cat#

Series.str.cat(others=None, sep=None, na_rep=None, join='left')[源代码]#

在 Series/Index 中使用给定的分隔符连接字符串。

如果指定了 others,此函数会逐元素地将 Series/Index 和 others 的元素连接起来。如果未传递 others,则 Series/Index 中的所有值将使用给定的 sep 连接成一个单一的字符串。

参数:
其他Series, Index, DataFrame, np.ndarray 或类列表

Series、Index、DataFrame、np.ndarray(一维或二维)以及其他类似列表的字符串必须与调用 Series/Index 的长度相同,除非是索引对象(即 Series/Index/DataFrame),如果 join 不为 None。

如果 others 是一个类似列表的对象,包含 Series、Index 或 np.ndarray(一维)的组合,那么所有元素将被解包,并且必须单独满足上述标准。

如果 others 为 None,该方法返回调用 Series/Index 中所有字符串的连接。

sepstr, 默认 ‘’

不同元素/列之间的分隔符。默认使用空字符串 ‘’

na_repstr 或 None, 默认 None

所有缺失值插入的表示:

  • 如果 na_rep 为 None,且 others 为 None,则 Series/Index 中的缺失值将从结果中省略。

  • 如果 na_rep 是 None,且 others 不是 None,在任何列中包含缺失值的行(在连接之前)将在结果中包含缺失值。

join{‘left’, ‘right’, ‘outer’, ‘inner’},默认 ‘left’

确定在调用 Series/Index 和 others 中的任何 Series/Index/DataFrame 之间的连接样式(没有索引的对象需要匹配调用 Series/Index 的长度)。要禁用对齐,请在 others 中的任何 Series/Index/DataFrame 上使用 .values

返回:
str, Series 或 Index

如果 others 是 None,则返回 str,否则返回一个 `Series/Index`(与调用者类型相同)的对象。

参见

split

在 Series/Index 中拆分每个字符串。

join

将作为 Series/Index 中的元素的列表连接起来。

例子

当不传递 others 时,所有值都被连接成一个单一的字符串:

>>> s = pd.Series(["a", "b", np.nan, "d"])
>>> s.str.cat(sep=" ")
'a b d'

默认情况下,Series 中的 NA 值会被忽略。使用 na_rep,它们可以被赋予一个表示:

>>> s.str.cat(sep=" ", na_rep="?")
'a b ? d'

如果指定了 others ,相应的值将与分隔符连接。结果将是一个字符串序列。

>>> s.str.cat(["A", "B", "C", "D"], sep=",")
0    a,A
1    b,B
2    NaN
3    d,D
dtype: object

缺失值在结果中将保持缺失,但可以使用 na_rep 再次表示。

>>> s.str.cat(["A", "B", "C", "D"], sep=",", na_rep="-")
0    a,A
1    b,B
2    -,C
3    d,D
dtype: object

如果未指定 sep,则值将无分隔地连接在一起。

>>> s.str.cat(["A", "B", "C", "D"], na_rep="-")
0    aA
1    bB
2    -C
3    dD
dtype: object

具有不同索引的系列可以在连接之前对齐。join-关键字在其他方法中也是如此工作。

>>> t = pd.Series(["d", "a", "e", "c"], index=[3, 0, 4, 2])
>>> s.str.cat(t, join="left", na_rep="-")
0    aa
1    b-
2    -c
3    dd
dtype: object
>>>
>>> s.str.cat(t, join="outer", na_rep="-")
0    aa
1    b-
2    -c
3    dd
4    -e
dtype: object
>>>
>>> s.str.cat(t, join="inner", na_rep="-")
0    aa
2    -c
3    dd
dtype: object
>>>
>>> s.str.cat(t, join="right", na_rep="-")
3    dd
0    aa
4    -e
2    -c
dtype: object

更多示例,请参见 这里