[英]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): 我有:两级索引
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
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
. 凡
process
新行添加到DF_country
。
Problem is in last string: 问题出在最后一个字符串中:
ValueError: Wrong number of items passed 2, placement implies 1 ValueError:传递的项目数错误2,展示位置暗含1
I just modify your code, I change the process
to add
, Base on my understanding process is a self-define function right ? 我只是修改您的代码,我更改
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.