[英]Need help dynamically adding to a dataframe using a variable number of columns
我做了一些文本分析,試圖循環一個數據框,該數據框由一列中的單詞列表和其他列中的一些數值組成。 我想將列表列中的所有單詞拆分為不同的行,並且還帶有位於同一行的值。 我希望代碼可以被我分享的其他人使用,所以我已經制作了代碼,以便他們必須在代碼中只提前一次輸入所需的列。
我設法循環數據框,在指定列名時拆分單詞並賦值,但是當我嘗試使循環動態時,我似乎無法正確獲取語法:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.