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

前端 未结 2 1714
旧巷少年郎
旧巷少年郎 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:03

    How about this - first define a function that takes a dataframe, and replaces the first x records with a specified value.

    def replace_first_x(group_df, x, value):
        group_df.iloc[:x, :] = value
        return group_df
    

    Then, pass that into the groupby object with apply.

    In [97]: df.groupby(level=0).apply(lambda df: replace_first_x(df, 2, 9999))
    Out[97]: 
                                   A            B            C            D
    CATEGORY DATE                                                          
    A        2000-01-01  9999.000000  9999.000000  9999.000000  9999.000000
             2000-01-03  9999.000000  9999.000000  9999.000000  9999.000000
             2000-01-05     1.590503     0.948911    -0.268071     0.622280
             2000-01-07    -0.493866     1.222231     0.125037     0.071064
    B        2000-01-02  9999.000000  9999.000000  9999.000000  9999.000000
             2000-01-04  9999.000000  9999.000000  9999.000000  9999.000000
             2000-01-06     1.663430    -1.170716     2.044815    -2.081035
             2000-01-08     1.593104     0.108531    -1.381218    -0.517312
    

提交回复
热议问题