如何将Pandas Series中的字符串数字拆分为单个数字元素列表?
解决Pandas Series拆分为单个数字列表的问题
问题场景
你有如下Pandas Series:
test # 输出: # 1 10011 # Name: working_days, dtype: object
需要将值中的每个数字作为独立整数元素存入列表,得到[1,0,0,1,1],而非直接提取整个值得到的[10011]。
实现代码
单元素Series处理
如果你的Series只有这一个元素,直接提取值后拆分转换即可:
import pandas as pd # 构造示例Series(已有则跳过) test = pd.Series(['10011'], index=[1], name='working_days') # 提取字符串值并拆分每个字符为整数 str_value = test.iloc[0] result = [int(char) for char in str_value] print(result) # 输出: [1, 0, 0, 1, 1]
多元素Series扩展处理
如果Series包含多行数据,可以用apply批量处理每行:
test = pd.Series(['10011', '11001'], name='working_days') result_list = test.apply(lambda x: [int(c) for c in x]).tolist() print(result_list) # 输出: [[1, 0, 0, 1, 1], [1, 1, 0, 0, 1]]
关键说明
直接用test.tolist()会把整个10011作为列表的单个元素,要实现拆分必须先将值转为字符串,逐个遍历字符并转换为整数,再组合成列表。
内容的提问来源于stack exchange,提问作者Carlos
相关产品推荐
相关产品推荐

