python-3.x - 熊猫数据框中的列级解析
问题描述
目前我正在处理 5 列的 20M 记录。我的数据框看起来像 -
tran_id id code
123 1 1759@1@83@0#1362@0.2600@25.7400@2.8600#1094@1@129.6@14.4
254 1 1356@0.4950@26.7300@2.9700
831 2 1354@1.78@35.244@3.916#1101@2@40@0#1108@2@30@0
732 5 1430@1@19.35@2.15#1431@3@245.62@60.29#1074@12@385.2@58.8#1109
141 2 1809@8@75.34@292.66#1816@4@24.56@95.44#1076@47@510.89@1110.61
所需的输出 -
id new_code
1 1759
1 1362
1 1094
1 1356
2 1354
2 1101
2 1108
5 1430
5 1431
5 1074
5 1109
2 1809
2 1816
2 1076
到目前为止我所做的 -
import re
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dd= pd.DataFrame({'col' : d["code"].apply(lambda x: re.split('[# @ ]', x))})
dd.head()
s = dd['col'].str[:]
dd= pd.DataFrame(s.values.tolist())
dd.head()
cols = range(len(list(dd)))
num_cols = len(list(dd))
new_cols = ['col' + str(i) for i in cols]
dd.columns = new_cols[:num_cols]
只要记住数据的大小是巨大的...... 2000万。不能做任何循环。
提前致谢
解决方案
您可以Series.str.findall
用于提取分隔符之间长度为 4 的整数:
#https://stackoverflow.com/a/55096994/2901002
s = df['code'].str.findall(r'(?<![^#])\d{4}(?![^@])')
#alternative
#s = df['code'].str.replace('[#@]', ' ').str.findall(r'(?<!\S)\d{4}(?!\S)')
numpy.repeat
然后通过withstr.len
和 flaten创建新的 DataFrame chain.from_iterable
:
from itertools import chain
df = pd.DataFrame({
'id' : df['id'].values.repeat(s.str.len()),
'new_code' : list(chain.from_iterable(s.tolist()))
})
print (df)
id new_code
0 1 1759
1 1 1362
2 1 1094
3 1 1356
4 2 1354
5 2 1101
6 2 1108
7 5 1430
8 5 1431
9 5 1074
10 5 1109
11 2 1809
12 2 1816
13 2 1076
推荐阅读
- reactjs - 状态如何用于反应
- angular - 如何在角度主机监听器中使用键盘组合键
- bash - bash:嵌套选择菜单,只有第一个选择有效,第二个选择无效
- mongodb - 执行时聚合搜索功能错误
- java - 如何从 Servlet 发出 GET 请求
- oracle-apex - oracle apex中调用或使用oracle数组包
- python - 按值计数分组中的值列错误
- generics - Rust 说函数参数的生命周期不够长,即使已经放置了适当的生命周期
- html-email - 某些基于 Web 的客户端中的电子邮件中断
- python - 如何从父标签中排除嵌套标签以将输出作为文本跳过链接(a)标签