python - 将 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
出了什么问题,如何将所有拆分的值保存到数组中?
解决方案
如果您所说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'之前,否则它永远不会匹配。
推荐阅读
- javascript - 交换变量 JS
- python - 使用不记名令牌和刷新令牌从 api 请求数据
- javascript - 是否有任何函数可用于使用 React Js Hook 查看新更新的数组状态?
- reactjs - 无法在不破坏父反应应用程序样式的情况下导入使用 Material UI 实现的 React 组件
- angular - 新窗口工作完成后重定向到旧窗口
- weblogic - 连接到 OEPE 中的 Oracle Weblogic Cloud 12c 服务器时出现异常
- javascript - 在创建期间设置数组长度是否有好处?
- sql - 从 2 个表中过滤并加入 2 个其他表
- reactjs - 在这种情况下如何单击按钮更改组件
- reactjs - 反应叠加层内的输入字段在模态中不起作用