V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
? Learn Python the Hard Way
Python Sites
? PyPI - Python Package Index
? http://diveintopython.org/toc/index.html
? Pocoo
值得关注的项目
? PyPy
? Celery
? Jinja2
? Read the Docs
? gevent
? pyenv
? virtualenv
? Stackless Python
? Beautiful Soup
? 结巴中文分词
? Green Unicorn
? Sentry
? Shovel
? Pyflakes
? pytest
Python 编程
? pep8 Checker
Styles
? PEP 8
? Google Python Style Guide
? Code Style from The Hitchhiker's Guide
songdg
V2EX  ?  Python

请教如何根据条件使用 numpy 函数生成一个新的数组

  •  
  •   songdg · 2023-02-15 16:50:20 +08:00 · 1311 次点击
    这是一个创建于 446 天前的主题,其中的信息可能已经有所发展或是发生改变。

    腾讯云最新优惠活动来了:云产品限时1折,云服务器低至88元/年 ,点击这里立即抢购:9i0i.cn/qcloud,更有2860元代金券免费领取,付款直接抵现金用,点击这里立即领取:9i0i.cn/qcloudquan

    (福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

    请教如何通过数组 A 、B 得到 C ,先判断 B 中是否有重复,然后在 A 中找最大的其余的设为 0 。 A = array([3.33, 1.18, 5.42, 4.12])、B = array([449, 3676, 10975, 10975])、C = array([3.33, 1.18, 5.42, 0])

    3 条回复  ?  2023-02-18 14:52:32 +08:00
    TimePPT
        1
    TimePPT  
       2023-02-15 17:38:03 +08:00   ?? 1
    import pandas as pd
    import numpy as np

    A = np.array([3.33, 1.18, 5.42, 4.12])
    B = np.array([449, 3676, 10975, 10975])
    df = pd.DataFrame(data={"A": A, "B": B})
    df["C"] = df.groupby("B")["A"].transform("max")
    df["C"] = df.apply(lambda row: 0 if row["C"] > row["A"] else row["C"], axis=1)
    df
    TimePPT
        2
    TimePPT  
       2023-02-15 17:38:37 +08:00
    随手写的,应该还有更简洁的写法
    songdg
        3
    songdg  
    OP
       2023-02-18 14:52:32 +08:00
    @TimePPT 谢谢帮助,我觉得还是写个函数来解决这个问题。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   6300 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 02:12 · PVG 10:12 · LAX 19:12 · JFK 22:12
    Developed with CodeLauncher
    ? Do have faith in what you're doing.


    http://www.vxiaotou.com