我正在使用帶有醫藥產品的資料框,我必須從名稱(字串)中提取劑量,然后用簡化的劑量形式更改原始產品名稱。
我所擁有的示例:
Name
'Prenoxad 2mg/2ml solution for injection pre-filled syringes'
我想要,存盤在一個新列中:
Name_reduced
'Prenoxad 1mg/ml solution for injection pre-filled syringes'
另一個例子是擁有250mg/5ml,并且想要擁有50mg/ml。
我想對資料框中需要減少劑量的每個產品執行此操作。并非所有產品的名稱中都有劑量,而且有些產品名稱中的劑量不同,不需要任何減少,例如:
Co-amoxiclav 250mg/125mg tablets
所以我認為最好的方法可能是只對包含和的產品應用減少方法'/',因為這種減少只需要在和存在時發生。也適用于名稱中沒有確切字串的產品,因為它只發生在已經減少形式的劑量上。'mg''ml''mg''ml''mg/ml'
我可以像這樣提取我想使用的字串部分:
txt = "Prenoxad 2mg/2ml solution for injection pre-filled syringes"
x = re.findall("\d. /*\d.{2}",txt)
print(x)
#['2mg/2ml']
但我不知道在此之后該怎么辦,這種“減少”方法的最佳方法是什么?
uj5u.com熱心網友回復:
假設 DataFrame 作為輸入,您可以使用自定義函式str.replace:
def simplify(m):
q1, u1, q2, u2 = m.groups()
q1, q2 = int(q1), int(q2)
if set([u1,u2])>{'mg', 'ml'}:
return f'{q1}{u1}/{q2}{u2}'
else:
q = q1/q2
if int(q) == q:
q = int(q)
return f'{q}{u1}/{u2}'
df['Name'] = df['Name'].str.replace('(\d )(..)/(\d )(..)', simplify, regex=True)
輸出(作為 Name2 列進行比較):
Name Name2
0 Prenoxad 2mg/2ml solution Prenoxad 1mg/ml solution
使用的輸入:
df = pd.DataFrame({'Name': ['Prenoxad 2mg/2ml solution']})
uj5u.com熱心網友回復:
你可以這樣做:
import re
txt = "Prenoxad 2mg/2ml solution for injection pre-filled syringes"
x = re.findall("\d. /*\d.{2}",txt)[0]
items = ['mg', 'ml', '/']
if all([item in x for item in items]):
mg, ml = re.findall(r"(\d )",txt)
ratio = float(mg)/float(ml)
txt.replace(x, f'{ratio}mg/ml')
txt
輸出:
'Prenoxad 1.0mg/ml solution for injection pre-filled syringes'
uj5u.com熱心網友回復:
首先,您需要正確處理您的文本的功能:
def reduce_name(txt):
re_digits = '(\d )mg/(\d )ml'
x = re.findall(re_digits,txt)
if len(x) > 0:
reduced_value = int(x[0][0]) // int(x[0][1])
reduced_txt = re.sub(re_digits, f'{reduced_value}mg/ml', txt)
return reduced_txt
else:
return txt
如果你想應用到整個列,你可以這樣做:
df['column_name'].apply(reduce_name)
請注意可能的具體情況并相應調整代碼:
- 檢查數值是否可以包含千位分隔符,例如 2,500mg/...
- 檢查空格是否可以出現在正則運算式中
- 檢查第一個值是否總是能被第二個整除而沒有余數
uj5u.com熱心網友回復:
您可以使用該fractions模塊撰寫一個降低比率的函式。然后,您可以使用re.subwith alambda來查找比率并替換它。
import re
from fractions import Fraction
def replace_ratio(ratio):
fraction = Fraction(int(ratio.group(1)), int(ratio.group(2)))
numerator = fraction.numerator
denominator = "" if fraction.denominator == 1 else fraction.denominator
return f"{numerator}ml/{denominator}mg"
def process_text(text):
return re.sub("(\d )mg/(\d )ml", lambda ratio: replace_ratio(ratio), text)
print(process_text("Prenoxad 2mg/2ml solution for injection pre-filled syringes"))
# -> Prenoxad 1ml/mg solution for injection pre-filled syringes
print(process_text("Prenoxad 10mg/3ml solution for injection pre-filled syringes"))
# -> Prenoxad 10ml/3mg solution for injection pre-filled syringes
print(process_text("Prenoxad 120mg/6ml solution for injection pre-filled syringes"))
# -> Prenoxad 20ml/mg solution for injection pre-filled syringes
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/459183.html
