我正在做一些文本分析,并试图通过一个数据帧循环,该数据帧由一列中的单词列表和其他列中的一些数值组成。我想将列表列中的所有单词拆分到不同的行中,并将同一行中的值与它们一起带来。我希望与我共享的其他人可以使用该代码,因此我编写了该代码,以便他们只需在代码的前面输入一次所需的列
当我指定列名时,我已经成功地在数据帧中循环,分割出单词和属性值,但是当我尝试使循环动态化时,我似乎无法获得正确的语法:
TokensTable = pd.DataFrame({'Token': [], 'Value1': [],'Value2': [],'Value3': []})
counter = 0
for index, row in metricsByToken2.iterrows(): #for each row in the dataframe with values and the token lists
for index2, token in enumerate(row[0]): #for each token in the list of tokens in each row
if token.isalpha(): #If the token doesnt contain punctuation then
token = token.lower() #lowercase the token
if token in stop_words: #if the token is a stop word then
del token #delete the token
else:
TokensTable.loc[counter] = [row[0][index2]] + [row[1]] + [row[2]] + [row[3]]
counter = counter + 1 #increase counter to move to the next row in new df
else:
del token
因此,如果列表['A','B','C']中有其他列200300400,那么我希望将其拆分为3行,例如'A',200300400,然后是'B',200300400和'C',200300400
到目前为止,上面的代码对我有效,但我手动指定了[Row[1]+[Row[2]等。[Row[0][index2]]在每次运行代码时都会出现,因此必须保留,但同一行上添加的其他列的数量每次都会更改。所需的列数将始终为len(TokensTable)-1,尽管如此,我需要以某种方式从0循环到len(TokensTable)-1,我猜,但到目前为止,我还没有运气弄清楚这一点,所以任何帮助都将非常感谢
输入示例:
╔══════════════════╦════════╦════════╦════════╗
║ Text ║ Value1 ║ Value2 ║ Value3 ║
╠══════════════════╬════════╬════════╬════════╣
║ ['A','B','C'] ║ 1 ║ 3 ║ 7 ║
║ ['A1','B1','C1'] ║ 2 ║ 4 ║ 8 ║
║ ['A2','B2','C2'] ║ 3 ║ 5 ║ 9 ║
╚══════════════════╩════════╩════════╩════════╝
输出示例:
╔═══════╦════════╦════════╦════════╗
║ Token ║ Value1 ║ Value2 ║ Value3 ║
╠═══════╬════════╬════════╬════════╣
║ A ║ 1 ║ 3 ║ 7 ║
║ B ║ 1 ║ 3 ║ 7 ║
║ C ║ 1 ║ 3 ║ 7 ║
║ A1 ║ 2 ║ 4 ║ 8 ║
║ B1 ║ 2 ║ 4 ║ 8 ║
║ C1 ║ 2 ║ 4 ║ 8 ║
║ A2 ║ 3 ║ 5 ║ 9 ║
║ B2 ║ 3 ║ 5 ║ 9 ║
║ C2 ║ 3 ║ 5 ║ 9 ║
╚═══════╩════════╩════════╩════════╝
感谢链接@HS星云它引导我找到了我需要的答案。 最后,我使用了一个循环来清理聚集的令牌,但为了取消它们的嵌套,我使用了以下方法:
相关问题 更多 >
编程相关推荐