![](/img/trans.png)
[英]Get index of the minimum of multi-index Pandas DataFrame using level
[英]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.