簡體   English   中英

迭代 pandas 列值

[英]Iterate over pandas column values

我有一個數據集,其中有一列字符串變量 (~6000) 描述了浴室類型(即 1 個私人浴室、2 個共用浴室等),有沒有辦法讓我“查找並替換”這些變量以簡化為簡單的數字, 1 個私人浴室更換為 integer 1,依此類推。

目前我嘗試使用 the.replace function 是一種冗長且低效的方法。

db["bathrooms_text"]= db["bathrooms_text"].replace("0 baths", 0)

db["bathrooms_text"]= db["bathrooms_text"].replace("1.5 baths", 1.5)

db["bathrooms_text"]= db["bathrooms_text"].replace("2 baths", 2)

使用str.extract

db['bathrooms_text'] = db['bathrooms_text'].str.extract('(\d+\.?\d*)')
print(db)

# Output
  bathrooms_text
0              0
1            1.5
2              2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM