【发布时间】:2020-06-17 09:23:39
【问题描述】:
尝试在我的数据框调用“方法”中创建一个新列。附图中的当前dataFrame:
我正在尝试使用 if/elif/else 以及正则表达式来创建新列,但是当我运行此代码时,我只得到来自 else 语句的值。为什么这不起作用,我该如何解决?
if 'posted' in df2.Full.astype(str) and '/ Outbound' in df2.TPrev.astype(str):
df2['Method']='Classifieds Homepage Button'
elif 'ad posted' in df2.Full.astype(str) and 'thanks' in df2.TPrev.astype(str):
df2['Method']='Header after Post'
elif 'ad posted' in df2.Full.astype(str) and '/myaccount/listing-classified Outbound' in df2.TPrev.astype(str):
df2['Method']='My Listings Button'
elif 'ad posted' in df2.Full.astype(str) and '/s/' in df2.TPrev.astype(str):
df2['Method']='SRP'
elif 'ad posted' in df2.Full.astype(str) and '/myaccount/listing-classified nan' in df2.TPrev.astype(str):
df2['Method']='My Listings Button'
elif 'ad posted' in df2.Full.astype(str) and '/sell nan nan' in df2.TPrev and '/myaccount/listing-classified nan nan' in df2.Prev.astype(str):
df2['Method']='My Listings Header'
elif 'ad posted' in df2.Full.astype(str) and '/listing/' in df2.TPrev.astype(str):
df2['Method']='Detail Page Header'
elif 'ad posted' in df2.Full.astype(str) and '/search/' in df2.TPrev.astype(str):
df2['Method']='SRP'
else:
df2['Method']='Ignore'
【问题讨论】:
-
您的逻辑语句评估为 整个 DataFrame 的 单个 真值,因此您只会将整个列设置为这些值之一.相反,您应该像在stackoverflow.com/questions/19913659/… 中一样使用
np.select在每一行中应用条件逻辑。您可能还希望将语句切换为df2.Full.astype(str).str.contains('ad posted')之类的内容,因为它们返回布尔系列。 -
正如上面的评论所说,每次执行都会覆盖
df2['Method']。除了np.select,您可以先创建一个空的df2['Method']列,然后使用循环填充您的条件。 -
您没有阅读 Pandas 文档吗?
标签: python regex pandas if-statement series