我有一個包含 3 列的數據框 df 和一個循環,根據循環的列名從文本文件創建字符串:exampletext = "Nr1 thisword1 and Nr2 thisword2 and Nr3 thisword3"Columnnames = ("Nr1", "Nr2", "Nr3")df1= pd.DataFrame(columns = Columnnames)for i in range(0,len(Columnnames)): solution = exampletext.find(Columnnames[i]) lsolution= len(Columnnames[i]) Solutionwords = exampletext[solution+lsolution:solution+lsolution+10]現在我想在正確字段中的數據幀 df1 的末尾附加 solutionwords,例如,在查找 Nr1 時,我想將 solutionwords 附加到名為 Nr1 的列。我嘗試使用 append 并創建一個列表,但這只會附加在列表的末尾。我需要數據框根據我要查找的單詞來分隔單詞。感謝您的任何幫助!編輯所需的輸出和可讀性:所需的輸出應該是一個數據框,如下所示:Nr1 | Nr2 | Nr3這個詞1 | thisword2 | 這個詞3
1 回答

慕標5832272
TA貢獻1966條經驗 獲得超4個贊
我假設你的單元格值總是跟在你的列名后面,并用空格分隔。在這種情況下,我可能會嘗試通過將您的值添加到字典中,然后在它包含您想要的數據后從中創建一個數據框來實現這一點,如下所示:
example_text = "Nr1 thisword1 and Nr2 thisword2 and Nr3 thisword3"
column_names = ("Nr1", "Nr2", "Nr3")
d = dict()
split_text = example_text.split(' ')
for i, text in enumerate(split_text):
if text in column_names:
d[text] = split_text[i+1]
df = pd.DataFrame(d, index=[0])
這會給你:
>>> df
Nr1 Nr2 Nr3
0 thisword1 thisword2 thisword3
添加回答
舉報
0/150
提交
取消