csv文件已发送给我/我无法重新分隔列
239845723,28374,2384234,AEVNE EFU 5 GN OR WNV,Owinv Vnwo Badvw 5 VIN,Ginq 2 jnwve wef evera wve 6 vwe as fgsb bfd bdfwd dsf (sdv seves 4-6), sebsbe sve(sevsev esvse 7-10) fsesef fesevsesv PaVvin (1 evesve vEV VEWee, 2 for WVEee VEWE. paper tuff as sWEFEWoon as VEWeew.).,2011-07-13 00:00:00,2011-07-13 00:00:00我替换了字符串字母来覆盖敏感信息,但是问题很明显。
这是我的csv中的一个例子“问题行”。它应按以下8列进行分类:
col1: 239845723
col2: 28374
col3: 2384234
col4: AEVNE EFU 5 GN OR WNV
col5: Owinv Vnwo Badvw 5 VIN
col6: Ginq 2 jnwve wef evera wve 6 vwe as fgsb bfd bdfwd dsf (sdv seves 4-6), sebsbe sve(sevsev esvse 7-10) fsesef fesevsesv PaVvin (1 evesve vEV VEWee, 2 for WVEee VEWE. paper tuff as sWEFEWoon as VEWeew.).
col7: 2011-07-13 00:00:00
col8: 2011-07-13 00:00:00正如您所看到的,第6列是出现问题的地方,因为字符串中有逗号,导致熊猫不正确地分隔和创建新列。我该如何解决这个问题?我在想regex会有帮助,也许通过下面的设置。任何帮助都是非常感谢的!
csvfile = open(filetrace)
reader = csv.reader(csvfile)
new_list=[]
for line in reader:
for i in line:
#not sure发布于 2017-07-29 01:22:38
因此,在不知道文件或数据的细节的情况下,我可以提供一个regex解决方案,如果数据是一致的(并且在第6栏末尾有句号),该解决方案可以工作。我们不需要使用csv模块和regex模块就可以做到这一点。
import re
# make the regex pattern here
pattern = r"([\d\.]*),([\d\.]*),([\d\.]*),([^,]*),([^,]*),(.*\.?),([\d\-\s:]*),([\d\-\s:]*)"
# open the file with 'with' so you don't have to worry about closing it
with open(filetrace) as f:
for line in f: # iterate through the lines
values = re.findall(pattern, line)[0] # re.findall returns a list
# literal of a tuple
# record the values somewherevalues这里是一个8元组,包含您在原始csv中的每个列的值,只要使用/存储它们就行了。
祝你好运!
发布于 2017-07-29 02:52:54
因为您确切地知道需要多少列,而且只有一个有问题的列,所以我们可以将前几列从左边分离出来,其余部分从右边分开。换句话说,您不需要regex
将文件读入单个字符串
csvfile = open(filetrace).read()制作pd.Series
s = pd.Series(csvfile.split('\n'))拆分s并将其限制为5个拆分,这应该是6列
df = s.str.split(',', 5, expand=True)现在将右侧分割为2次。
df = df.iloc[:, :-1].join(df.iloc[-1].str.rsplit(',', 2, expand=True))从s开始的另一种方式
left = s.str.split(',', 5)
right = left.str[-1].str.rsplit(',', 2)
df = pd.DataFrame(left.str[:-1].add(right).tolist())我运行这个,并采取转置,使它更容易在屏幕上阅读。
df.T
0
0 239845723
1 28374
2 2384234
3 AEVNE EFU 5 GN OR WNV
4 Owinv Vnwo Badvw 5 VIN
5 Ginq 2 jnwve wef evera wve 6 vwe as fgsb bfd b...
6 2011-07-13 00:00:00
7 2011-07-13 00:00:00https://stackoverflow.com/questions/45384197
复制相似问题