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。
- Parameters:
- othersSeries、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, default ‘’
不同元素/列之间的分隔符。默认为空字符串 ‘’。
- na_repstr 或 None,默认为 None
为所有缺失值插入的表示:
如果 na_rep 为 None,且 others 为 None,则 Series/Index 中的缺失值将从结果中省略。
如果 na_rep 为 None,且 others 不为 None,则包含任何列中缺失值的行(连接前)将在结果中产生缺失值。
- <strong>join</strong>{‘left’, ‘right’, ‘outer’, ‘inner’},默认为 ‘left’
确定调用 Series/Index 与 others 中的任何 Series/Index/DataFrame 之间的连接样式(没有索引的对象需要匹配调用 Series/Index 的长度)。要禁用对齐,请在 others 中的任何 Series/Index/DataFrame 上使用 .values。
- Returns:
- str、Series 或 Index
如果 others 为 None,则返回 str,否则返回一个对象(与调用者相同的类型)的 Series/Index。
Examples
当不传递 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,则相应的值会与分隔符连接。结果将是一个字符串 Series。
>>> 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
具有不同索引的 Series 可以在连接前进行对齐。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
更多示例,请参阅 here 。