Pandas Series.str.split(~) 方法对系列中的每个字符串执行拆分。
参数
1.pat | string | optional
用于分割字符串的字符串或正则表达式模式。默认情况下,pat=" "(单个空格)。
2. n | int | optional
每个值允许的分割数。默认情况下,没有限制。请注意,参数值 None 、 0 或 -1 将被解释为无限制。
3. expand | boolean | optional
-
如果
True,则返回的列表将水平扩展为单独的列。 -
如果
False,则为每个值返回一个列表。
默认情况下,expand=False 。
返回值
如果 expand=True ,则返回 DataFrame /MultiIndex。否则,返回 Series /Index。
例子
基本用法
考虑以下系列:
s = pd.Series(["a","a_1","a_2"])
s
0 a
1 a_1
2 a_2
dtype: object
要按 _ 分割每个字符串:
s.str.split("_")
0 [a]
1 [a, 1]
2 [a, 2]
dtype: object
请注意系列中的每个值现在都是一个列表。
使用正则表达式
可以直接使用正则表达式作为分隔符:
s = pd.Series(["a_1","a*2"])
s.str.split(r'[_*]')
0 [a, 1]
1 [a, 2]
dtype: object
指定n
默认情况下,可以进行的拆分数量没有限制:
s = pd.Series(["a_1","a_2_3"])
s.str.split("_")
0 [a, 1]
1 [a, 2, 3]
dtype: object
允许每个值最多进行 1 拆分:
s.str.split("_", n=1)
0 [a, 1]
1 [a, 2_3]
dtype: object
指定展开
默认情况下, expand=False ,这意味着每个值都成为一个列表:
s = pd.Series(["a", "a_1","a_2"])
s.str.split("_")
0 [a]
1 [a, 1]
2 [a, 2]
dtype: object
您可以通过设置 expand=True 来扩展列表,如下所示:
s.str.split("_", expand=True) # returns a DataFrame
0 1
0 a None
1 a 1
2 a 2
处理缺失值
单个缺失值 ( NaN ) 的拆分结果也是 NaN :
s = pd.Series(["a_1",pd.np.NaN])
s.str.split("_")
0 [a, 1]
1 NaN
dtype: object
相关用法
- Python Pandas Series str strip方法用法及代码示例
- Python Pandas Series str extractall方法用法及代码示例
- Python Pandas Series str center方法用法及代码示例
- Python Pandas Series str pad方法用法及代码示例
- Python Pandas Series str extract方法用法及代码示例
- Python Pandas Series str replace方法用法及代码示例
- Python Pandas Series str len方法用法及代码示例
- Python Pandas Series str lower方法用法及代码示例
- Python Pandas Series str rstrip方法用法及代码示例
- Python Pandas Series str lstrip方法用法及代码示例
- Python Pandas Series string contains方法用法及代码示例
- Python Pandas Series to_list方法用法及代码示例
- Python Pandas Series between方法用法及代码示例
- Python Pandas Series map方法用法及代码示例
- Python Pandas Series hasnans属性用法及代码示例
- Python Pandas Series is_monotonic属性用法及代码示例
- Python Pandas Series to_frame方法用法及代码示例
- Python Pandas Series zfill方法用法及代码示例
- Python Pandas Series argmax方法用法及代码示例
- Python Pandas Series is_monotonic_increasing属性用法及代码示例
- Python Pandas Series is_unique属性用法及代码示例
- Python Pandas Series argmin方法用法及代码示例
- Python Pandas Series value_counts方法用法及代码示例
- Python Pandas Series is_monotonic_decreasing属性用法及代码示例
- Python Pandas Series.cumsum()用法及代码示例
注:本文由纯净天空筛选整理自Isshin Inada大神的英文原创作品 Pandas Series str | split method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
