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

2024-05-19 01:34:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从文件中清除数据。我已经做了部分清理,数据如下所示

enter image description here

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

Str '80 per piece' =>

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

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

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

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

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

enter image description here

但是如果我尝试使用掩码-我会得到这个错误

enter image description here


Tags: 数据代码piece错误unitcolumn数字条件
1条回答
网友
1楼 · 发布于 2024-05-19 01:34:48

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

相关问题 更多 >

    热门问题