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

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

通過 DataFrame 中的 ForLoop 賦值

通過 DataFrame 中的 ForLoop 賦值

四季花海 2023-10-06 18:50:04
我有一個這樣的數據庫:manufacturer  cylinders    description0   toyota   5 cylinders   toyota, gmc 10 years old.1   NaN          NaN       gmc, Motor runs and drives good.2   NaN          NaN       Motor old, in pieces. 4 cylinders3   NaN     12 cylinders   2 owner 0 rust. Cadillac.還有這組關鍵詞:manufacturer = ['gmc', 'toyota', 'cadillac']cylinders = ['12 cylinders', '4 cylinders', '5 cylinders']我想創建一個程序來讀取描述并根據所需的關鍵字向每列添加正確的信息。理想情況下,它看起來像這樣:    manufacturer  cylinders   description0   toyota      5 cylinders   toyota, gmc 10 years old.1   gmc             NaN       gmc, Motor runs and drives good.2   NaN         4 cylinders   Motor old, in pieces. 4 cylinders3   cadillac   12 cylinders   2 owner 0 rust. Cadillac.一直在嘗試一切,但似乎沒有任何效果。這是我為了將單詞添加到一列而嘗試的方法,但我需要將其更改為多個列,并且該程序會更改值,即使它不是 NaN(fe 將“toyota”更改為“gmc”),這是我不想要的。import rekeyword = ['gmc', 'toyota', 'cadillac']bag_of_words = []for i, description in enumerate(test3['description']):bag_of_words = re.findall(r"""[A-Za-z\-]+""", test3["description"][i])for word in bag_of_words:     if word.lower() in keyword:            test3.loc[i, 'manufacturer'] = word.lower()我知道如何解決這個問題嗎?謝謝。
查看完整描述

1 回答

?
元芳怎么了

TA貢獻1798條經驗 獲得超7個贊

無需使用 for 循環。相反,您可以使用pandas矢量化函數。

  1. 您可以與庫fillna()一起使用。本質上,您正在用從描述列中提取的信息替換值。.str.extract()pandasNaN

  2. 您可以傳遞一個標志,flags=re.IGNORECASE以在匹配時忽略大小寫。

  3. 最后,我們必須使用, expand=False返回一個系列,因為返回一個數據幀,這在處理數據幀而不是系列str.extract()時會導致錯誤。.fillna()

import pandas

import re

keyword = ['gmc', 'toyota', 'cadillac']

df['manufacturer'] = df['manufacturer'].fillna(

    df['description'].str.extract('(gmc|toyota|cadillac)', flags=re.IGNORECASE, expand=False))

df['cylinders'] = df['cylinders'].fillna(

    df['description'].str.extract('(\d+\s+cylinders?)', flags=re.IGNORECASE, expand=False))

df

Out[1]: 

  manufacturer     cylinders                        description

0       toyota   5 cylinders          toyota, gmc 10 years old.

1          gmc           NaN   gmc, Motor runs and drives good.

2          NaN   4 cylinders  Motor old, in pieces. 4 cylinders

3     Cadillac  12 cylinders          2 owner 0 rust. Cadillac.

如果您需要輸出為小寫,您可以將str.lower()或添加str.casefold()到每列上面每行代碼的末尾。操作與符號和不同語言casefold()類似lower(),但更可靠。


查看完整回答
反對 回復 2023-10-06
  • 1 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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