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

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

在函數中使用匹配組作為參數

在函數中使用匹配組作為參數

桃花長相依 2022-06-14 16:50:50
我有一個數據框,我們有美國符號的人的大小,我想用正則表達式(或其他......)替換這些以厘米為單位的值#approximationdef conversion(one, two):    print(one)    return (int(one)*30 + float(int(two)*2.5))df_test = df_dummiesdf_test['Height'] = df_test['Height'].replace({r'(\w+)\+(\w+)' : conversion( r'\1' , r'\2' )}, regex=True).astype(float)我已經嘗試過了,但是匹配的組不起作用錯誤 :---------------------------------------------------------------------------ValueError                                Traceback (most recent call last)<ipython-input-189-d4278403d30f> in <module>      5       6 df_test = df_dummies----> 7 df_test['Height'] = df_test['Height'].replace({r'(\w+)\+(\w+)' : conversion( r'\1' , r'\2' )}, regex=True).astype(float)      8 df_test.head().transpose()<ipython-input-189-d4278403d30f> in conversion(one, two)      2 def conversion(one, two):      3     print(one)----> 4     return (int(one)*30 + float(int(two)*2.5))      5       6 df_test = df_dummiesValueError: invalid literal for int() with base 10: '\\1'但如果我這樣做:#approximationdef conversion(one, two):    print(one)    return (int(one)*30 + float(int(two)*2.5))df_test = df_dummiesdf_test['Height'] = df_test['Height'].replace({r'(\w+)\+(\w+)' : r'\1' +r'\2' }, regex=True).astype(float)它工作正常,我得到了 2 個匹配組的串聯有沒有一種解決方案可以將結果轉換(一,二)作為數據框中的替換?
查看完整描述

1 回答

?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

使用支持回調的Series.str.replace()作為替換。


def conversion(m): 

    return str(int(m.group(1))*30 + float(int(m.group(2))*2.5))


df_test['Height'] = df_test['Height'].str.replace(r'(\d+)\+(\d+)', conversion).astype(float)

回調函數采用一個參數,即正則表達式匹配對象。您將需要返回一個字符串作為替換。


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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