How to Update Value in First N Rows by Group in a Multi-Index Pandas Dataframe?

前端 未结 2 1746
旧巷少年郎
旧巷少年郎 2021-01-22 11:51

I am attempting to update the first N rows in a multi-index dataframe but was having a bit of trouble finding a solution so thought I\'d create a post for it.

The exampl

2条回答
  •  不要未来只要你来
    2021-01-22 12:12

    Typically, whenever you have to change values, rather then just pick them, you cannot proceed using a lambda function only, since these only allow selection.

    A very boiled down way to proceed is

    def replace_first(group):
        group.iloc[0:2] = 99
        return group
    

    and then just do

    In[144]: df.groupby(level=0).apply(replace_first)
    Out[144]: 
                                 A          B          C          D
    CATEGORY DATE                                                  
    A        2000-01-01  99.000000  99.000000  99.000000  99.000000
             2000-01-03  99.000000  99.000000  99.000000  99.000000
             2000-01-05   0.458031   1.959409   0.622295   0.959019
             2000-01-07   0.934521  -2.016685   1.046456   1.489070
    B        2000-01-02  99.000000  99.000000  99.000000  99.000000
             2000-01-04  99.000000  99.000000  99.000000  99.000000
             2000-01-06  -0.117322  -1.664436   1.582124   0.486796
             2000-01-08  -0.225379   0.794846  -0.021214  -0.510768
    

提交回复
热议问题