简体   繁体   中英

Pandas: Assign multi-index DataFrame with with DataFrame by index-level-0

Please, suggest a more suitable title for this question

I have: Two-level indexed DF (crated via groupby):

                    clicks  yield
country report_date     
AD      2016-08-06    1      31
        2016-12-01    1      0
AE      2016-10-11    1      0
        2016-10-13    2      0

I need:

Consequently take country by country data, process it and put it back:

for country in set(DF.get_level_values(0)):
    DF_country  = process(DF.loc[country])
    DF[country] = DF_country

Where process add new rows to DF_country .

Problem is in last string:

ValueError: Wrong number of items passed 2, placement implies 1

I just modify your code, I change the process to add , Base on my understanding process is a self-define function right ?

for country in set(DF.index.get_level_values(0)): # change here
    DF_country  = DF.loc[country].add(1)
    DF.loc[country] = DF_country.values #and here
DF
Out[886]: 
                     clicks  yield
country report_date               
AD      2016-08-06        2     32
        2016-12-01        2      1
AE      2016-10-11        2      1
        2016-10-13        3      1

EDIT :

l=[]

for country in set(DF.index.get_level_values(0)):
    DF1=DF.loc[country]
    DF1.loc['2016-01-01']=[1,2] #adding row here
    l.append(DF1)


pd.concat(l,axis=0,keys=set(DF.index.get_level_values(0)))

Out[923]: 
                clicks  yield
   report_date               
AE 2016-10-11        1      0
   2016-10-13        2      0
   2016-01-01        1      2
AD 2016-08-06        1     31
   2016-12-01        1      0
   2016-01-01        1      2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM