亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python附加到數據框中的特定列

Python附加到數據框中的特定列

墨色風雨 2021-08-17 17:15:21
我有一個包含 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


查看完整回答
反對 回復 2021-08-17
  • 1 回答
  • 0 關注
  • 164 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號