首页 > 解决方案 > 将 pandas.DataFrame 列的字符串值拆分为数组

问题描述

我从 postgresql 做了一些 sql 请求,并将其设置为 pandas.DataFrame()。每行看起来像: '8B1LP1D' 其中字母('B' , 'LP' 等)是分隔符而这种方法:

#formula is a pd.DataFrame with 1 column
for x in formula:
    print(re.split('B|LP|D|E|OS|DN',x))

输出看起来不错:

['8', '1', '1']
...
['5', '3', '2']
#etc

但我必须将它附加到数组中:

def move_parts(a):
    split = []
    for x in a:
        split.append(re.split('B|LP|D|E|OS|DN',x))
move_parts(formula)

结果像错误一样返回:

/usr/lib/python3.7/re.py in split(pattern, string, maxsplit, flags)
    211     and the remainder of the string is returned as the final element
    212     of the list."""
--> 213     return _compile(pattern, flags).split(string, maxsplit)
    214 
    215 def findall(pattern, string, flags=0):

TypeError: expected string or bytes-like object

出了什么问题,如何将所有拆分的值保存到数组中?

标签: pythonstringpandastypessplit

解决方案


如果您所说formula的带有 1 列,则您的第一个表达式会给出相同的错误。pd.DataFrame改用熊猫split

df = pd.DataFrame({'col1': ['8B1LP1','5E3DN2']})
df.iloc[:,0].str.split('B|LP|DN|E|OS|D',expand=True).values.tolist()

输出:

[['8', '1', '1'], ['5', '3', '2']]

PS:你应该重新排序你的分隔符(如我的例子所示):更长的'DN'必须单个'D'之前,否则它永远不会匹配。


推荐阅读