python - 如果满足特定条件,则在 panda 数据框中添加列值

标签 python pandas dataframe

我有两个列表:

    required=["api.gotinder.com","data.gotinder.com"]
    not_required=["graph.facebook.com","launches.appsflyer.com"]

如果requested_server_name列中的值在必需列表中,则应将其标记为必需,如果requested_server_name列中的值在not_required列表中,则应将其标记为Not_Required

我现在在做什么:

for j in required:
    conditions = [
        (frame['requested_server_name'] == j)
        ]
    values = ["Required"]
    frame['label'] = np.select(conditions, values)

for k in not_required:
    conditions = [
        (frame['requested_server_name'] == k)
        ]
    values = ["Not_Required"]
    frame['label'] = np.select(conditions, values)

我做错了什么?它仅填充 launch.appsflyer.com 的标签。

最佳答案

创建一个dict,然后反转键和值以创建映射字典。最后使用 replace 应用映射:

d = {'required': ["api.gotinder.com", "data.gotinder.com"],
     'not_required': ["graph.facebook.com", "launches.appsflyer.com"]}

MAP = {v: k for k, l in d.items() for v in l}

frame['label'] = frame['requested_server_name'].replace(MAP)

关于python - 如果满足特定条件,则在 panda 数据框中添加列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71100664/

相关文章:

python - 按标签系列重新索引 DataFrame 列

python - SQLAlchemy LazyLoading 的工作原理

python - 如何通过使用 bash 脚本传递参数来运行 python 文件?

python - Lua 支持装饰器吗?

python numpy - 提高列余弦相似度的效率

r - 变异列以检测变体数量

python - 在整个数据框中查找最大值和相应的列/索引名称

python - 将两个列表列表压缩在一起 - Python

python - 计算每列的不同值,返回数据框并对值进行排序

r - 使用 as.data.frame() 在 R 中复制行名称