簡體   English   中英

熊貓:通過索引級別0將多索引DataFrame與DataFrame一起分配

[英]Pandas: Assign multi-index DataFrame with with DataFrame by index-level-0

請為這個問題建議一個更合適的標題

我有:兩級索引DF (通過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

我需要:

因此,按國家/地區獲取數據,對其進行處理並放回去:

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

process新行添加到DF_country

問題出在最后一個字符串中:

ValueError:傳遞的項目數錯誤2,展示位置暗含1

我只是修改您的代碼,我更改add process ,根據我的理解過程是自定義函數吧?

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

編輯:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM