繁体   English   中英

嵌套 for 循环将非结构化数据转换为结构化数据

[英]Nested for loops to convert unstructured data to structured

我正在尝试将非结构化数据转换为 Python 中的结构化数据,并且需要一些帮助。 我的数据集有一个名为“评论”的自由文本列,此时有 143 行。 我需要根据 Comments 列中的信息创建三个附加字段。 下面是示例输入数据。 我需要提取 Phone_Call、Successful 和 Yes 作为三个词,然后将它们输入单独的列。 所有 rest 对我来说都是无用的信息。

-- 类型: Phone_Call联系尝试:成功验证完成:备注:联系客户并且联系尝试成功,完成验证。

-- 类型:Email 联系尝试:不成功验证完成:否 备注:联系客户,联系尝试成功,完成验证。

这就是我处理这个问题的方式:

  1. 我将 Comments 列转换为 String 类型。
  2. 我创建了一个 for 循环来拆分每一行的评论(我在空格处拆分)
  3. 我将创建第二个嵌套 for 循环,然后选择第 3、7 和 10 个单词
  4. 最后,我将创建第三个嵌套循环,然后获取第 3、7 和第 10 个单词并将它们转移到三个不同的列中。

我已经能够完成第一步和第二步,但在那之后我有点卡住了。 不知道如何创建嵌套的 for 循环。 有什么建议么? 到目前为止,我编写的代码如下:

评论 = df['COMMENTS'].astype(str)

for i in range(len(comments)): (str.split(comments[i]))

谢谢!

阵列拼接将是你的朋友。

a="Type:Phone_Call Contact Attempt:Successful Validation 
Complete:Yes Notes: Reached out to the customer and contact 
attempt was successful, completed validation"
b= a.split(" ")

c=[None,None,None]
c[0]=b[0][5:]
c[1]=b[2][7:]

如果“垃圾”在“:”字符之前发生变化,您可以使用 index(“:”) 设置拼接标记。

我能够解决它。 感谢卡车装载@IGotThis。 你的建议让我开始了。 这是我的完整代码。

comments = df['COMMENTS'].tolist()

# For loop to split the comments list by whitespace and store in list e
e = []

for i in range(len(comments)):
    e.append(str.split(comments[i]))

#Extract all the important information and store in list c       
c = []

for j in range(len(e)):
    c.append(e[j][2][0:])
    c.append(e[j][6][0:])
    c.append(e[j][9][0:])

#Split list c into groups of 3 elements and write to a new dataframe

data = list(zip(*[iter(c)]*3))

f= pd.DataFrame(data[0:], columns=['Contact Type', 'Contact Made', 'Verification Complete'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM