Pandas:使用regex替换列中的值

2024-06-06 15:16:05 发布

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

我有2个数据帧,我需要使用第二个数据帧中的值将新列添加到第一个数据帧 第一个方向是

ID,"url","used_at","active_seconds"
8075643aab791cec7dc9d18926958b67,"sberbank.ru/ru/person/promo/10mnl?utm_source=Vesti.ru&utm_medium=html&utm_campaign=10_million_users_SBOL_dec2015&utm_term=every14_syncbanners",2016-01-01 00:03:16,183
a04a8041ffa6fe1b85471ca5af1ee575,"online.rsb.ru/hb/faces/system/login/rslogin.jsp?credit=false",2016-01-01 00:04:36,42
a04a8041ffa6fe1b85471ca5af1ee575,"online.rsb.ru/hb/faces/system/login/sms/sms.jsp?smsAuth=true",2016-01-01 00:05:18,22
a04a8041ffa6fe1b85471ca5af1ee575,"online.rsb.ru/hb/faces/rs/RSIndex.jspx",2016-01-01 00:05:40,14
a04a8041ffa6fe1b85471ca5af1ee575,"online.rsb.ru/hb/faces/rs/payments/PaymentReq.jspx",2016-01-01 00:05:54,22
ba880911a6d54f6ea6d3145081a0e0dd,"homecredit.ru/help/quest/feedback.php",2016-01-01 00:06:12,2

第二个测向看起来像

^{pr2}$

如果我没有正则表达式,我使用

df1['code'] = df1.url.map(df2.set_index('URL')['Code'])

但我不能这样做,因为df2.URL是regex。 但是

df1['code'] = df1['url'].replace(df2['URL'], df2['Code'], regex=True)

不起作用。在


Tags: 数据urlruloginsystemonlinedf1utm
1条回答
网友
1楼 · 发布于 2024-06-06 15:16:05

根据我的评论,pandas.Series.replace()方法不允许Series对象作为to_replace和{}参数。传递列表反而起作用:

df1['code'] = df1.url.replace(df2.URL.values, df2.Code.values, regex=True)
print df1[['url', 'code']]

生成以下输出:

^{pr2}$

为了回答您的附加注释,您不能在df1.code中的df2.Codedf1.url与任何regex字符串都不匹配的行中,但是您可以为这些情况提供一个值(例如None)以将其放入列中。例如,可以通过添加以下行来完成:

df1['code'] = df1.apply(lambda x: None if x.code == x.url else x.code, axis=1)

其中print df1[['url', 'code']]返回以下内容:

                                                 url  code
0  sberbank.ru/ru/person/promo/10mnl?utm_source=V...   NaN
1  online.rsb.ru/hb/faces/system/login/rslogin.js...   NaN
2  online.rsb.ru/hb/faces/system/login/sms/sms.js...   NaN
3             online.rsb.ru/hb/faces/rs/RSIndex.jspx   NaN
4  online.rsb.ru/hb/faces/rs/payments/PaymentReq....   NaN
5              homecredit.ru/help/quest/feedback.php  15.0

相关问题 更多 >