首页 > 解决方案 > 如果值为浮点数,则选择 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"
如何仅选择具有浮点值的数据框部分?
(在本专栏中,我只等待字符串作为数据类型)

标签: pythonpandas

解决方案


用于Series.fillna填充NaN值,然后您可以使用Series.str.containswithnp.whereSeries.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"})

我建议你看看:when should I want to use apply


推荐阅读