python - 如果值为浮点数,则选择 Pandas 数据框中的行
问题描述
def categorizeMainUrl(url):
category = "other"
if "/special/" in url:
category = "special"
return category
df["category"] = df["main_URL"].apply(lambda url: categorizeMainUrl(url))
在运行这部分代码时,我保留了以下异常。
"TypeError: argument of type 'float' is not iterable"
如何仅选择具有浮点值的数据框部分?
(在本专栏中,我只等待字符串作为数据类型)
解决方案
用于Series.fillna
填充NaN
值,然后您可以使用Series.str.contains
withnp.where
或Series.map
创建一个新系列:
df["category"] = np.where(df['main_URL'].fillna('').str.contains('/special/'),
"special", "other")
或者
df["category"] = (df['main_URL'].fillna('')
.str.contains('/special/')
.map({True:"special",
False:"other"})
)
#df['main_URL'].fillna('').str.contains('/special/').replace({True:"special",
# False:"other"})