Pandas - 仅对基于特定条件检索的行使用正则表达式提取的数字/字符串更新列

Pandas - Update column with numbers / string extracted by using regex only on rows retrieved based on specific conditions

我正在尝试清除文件中的数据。我做了部分清理,数据看起来像这样。

Price 列仍需要清理并更新到其他列中。这就是我想要做的

Str '80 per piece' =>

80 -> 'Price' column
'piece' -> 'Unit' column

Str '110 per pack' =>
110 -> 'Price' column
'pack' -> 'Unit' column

我创建了一个掩码来检索我需要的行,然后使用正则表达式提取非数字。我发现它会影响所有行。当我尝试仅使用掩码检索到的行时 - 我收到错误消息。

如何确保只有条件检索行中的列受到影响?

这是我的代码 - 两边都没有使用掩码,输出不正确。

但是如果我使用遮罩尝试此操作 - 我会收到此错误

IIUC 您可以 extract 命名组,然后 update:

df = pd.DataFrame({"Unit":["gm", np.NaN, np.NaN],
                   "Price":["40","80 per piece", "110 per pack"]})

  Unit         Price
0   gm            40
1  NaN  80 per piece
2  NaN  110 per pack

s = df.loc[df["Unit"].isnull(),"Price"].str.extract("(?P<Price>\d+)\sper\s(?P<Unit>[A-Za-z]+)").dropna()

df.update(s)

print (df)

    Unit Price
0     gm    40
1  piece    80
2   pack   110