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 · 1292 次点击
    这是一个创建于 434 天前的主题,其中的信息可能已经有所发展或是发生改变。

    请教如何通过数组 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   ·   我们的愿景   ·   实用小工具   ·   5436 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 07:06 · PVG 15:06 · LAX 00:06 · JFK 03:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.