Pandas:通过indexlevel0为DataFrame分配多索引DataFrame

2024-04-29 14:54:30 发布

您现在位置:Python中文网/ 问答频道 /正文

请为这个问题建议一个更合适的标题

我有:两级索引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

其中processDF_country添加新行。你知道吗

问题在最后一个字符串中:

ValueError:传递的项数错误2,位置意味着1


Tags: 数据report标题dfdate国家processcountry
1条回答
网友
1楼 · 发布于 2024-04-29 14:54:30

我只是修改了你的代码,我把process改成了add,基于我的理解过程是一个自定义函数吧?你知道吗

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

相关问题 更多 >