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
bleutail
V2EX  ›  Python

pandas 相关的问题,请问如何在 df 分类 groupby 的同时实现条件赋值,修改每一类前几行和最后几行的值为空值

  •  
  •   bleutail · 2022-05-17 00:03:37 +08:00 · 1563 次点击
    这是一个创建于 681 天前的主题,其中的信息可能已经有所发展或是发生改变。
    def fuc(x):
        x.loc[(x.head(10).index) & (x.tail(10).index),'col_name'] = np.nan
        return x
    df['col_name'] = df.groupby('date').apply(fuc)['col_name']```
    
    以上写法没报错,但也没实现修改效果。。
    2 条回复    2022-05-17 14:32:37 +08:00
    robbielj
        1
    robbielj  
       2022-05-17 10:11:02 +08:00
    ```
    def fuc(x):
    x.loc[np.r_[x.head(10).index.values,x.tail(10).index.values]] = np.nan
    return x
    df['col'] = df.groupby('date')["col"].apply(fuc)

    ```
    milkpuff
        2
    milkpuff  
       2022-05-17 14:32:37 +08:00
    apply 每个 group 返回一个值, m 行数据、n 个 group -> 返回 n 行
    transfer 返回 shape 和原来一致 m 行数据、n 个 group -> 返回 m 行
    你这个应该使用 transfer
    另外,(x.head(10).index) & (x.tail(10).index)这句也不是拼接两个 index, 参考 1 楼
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3259 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:13 · PVG 20:13 · LAX 05:13 · JFK 08:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.