python - 需要帮助使用可变数量的列动态添加到数据框
问题描述
我正在做一些文本分析,并尝试遍历一个数据框,该数据框由一列中的单词列表和其他列中的一些数值组成。我想将列表列中的所有单词拆分到不同的行上,并将它们放在同一行上的值。我希望我与之共享的其他人可以使用该代码,因此我制作了代码,以便他们只需在代码的前面输入一次所需的列。
我已经设法遍历数据框,在指定列名时拆分单词并属性值,但是当我尝试使循环动态时,我似乎无法正确使用语法:
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'] 与其他列 200,300,400 则我希望将其拆分为 3 个单独的行,例如:'A',200,300,400 然后 'B',200,300,400 和' C',200,300,400。
到目前为止,上面的代码对我有用,但我手动指定了 [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-nebula 的链接,它让我找到了我需要的答案。最后,我使用了一个循环来清理聚合的令牌,但为了取消嵌套它们,我使用了以下内容:
TokensTable = metricsByToken2.apply(lambda x: pd.Series(x['Token']),axis=1).stack().reset_index(level=1, drop=True)
TokensTable.name = 'Token'
TokensTable = metricsByToken2.drop('Token', axis=1).join(TokensTable)
TokensTable = TokensTable.reset_index(drop=True)
推荐阅读
- objective-c - 在目标 c 中编码 URL 参数
- ios - 在 Xcode 11 中为旧源代码启用自动布局
- javascript - 我可以在没有服务器的情况下执行此操作吗?
- java - 返回“”是什么意思?
- jquery - 从使用 jQuery 发出 GET 请求的函数返回数组
- java - 用于将日志/记录重定向到远程服务器的 Java 命令行选项
- python-3.x - Image Magick 命令的等效 OpenCV 代码
- asp.net - Visual Basic - 如何为下拉列表中的 SelectedIndex 项分配值?
- javascript - 在 vuejs 中调用嵌套方法
- xml - 在 vb.net 中的 xDocument 的 xml 标记中添加条件