简体   繁体   中英

How to add a pd.Series to a subset of multi-index DataFrame?

I have a multi-index dataframe created by:

arrays = [['task_1','task_2', 'task_2'],['accuracy', 'accuracy', 'precision']]
mux = pd.MultiIndex.from_arrays(arrays, names=('task', 'metric'))
data = [[4., 5., 6.], [1., 1., 1.]]
res = pd.DataFrame(data, columns=mux, index=['total', 'counts']).transpose()

>>> res                  
                   total  counts
task   metric                  
task_1 accuracy     4.0     1.0
task_2 accuracy     5.0     1.0
       precision    6.0     1.0

Now I want to update the total column of task_2 by adding [0.1, 0.2] to task_2.accuracy and task_2.precision respectively:

update = pd.Series([0.1, 0.2], index=['accuracy', 'precision'])
res.total.task_2 += update

>>> res
                  total  counts
task   metric                  
task_1 accuracy     4.0     1.0
task_2 accuracy     NaN     1.0
       precision    NaN     1.0

Why I get NaN ? Learning from another question , I also tried two ways attempting to match indices between update and res.total.task_2 . However, neither of them worked in my case.

res.total.task_2 += update.values
# -OR-
res.total.task_2 += update.reset_index(drop=True, inplace=True)

We have an option of adding on level, which we can use with series.xs to add only on the desired 0th level, then reindex and add:

res['total'] = (res['total'].xs("task_2",drop_level=False)
                .add(update,level=1).reindex(res.index)
                .fillna(res['total']))
print(res)

                  total  counts
task   metric                  
task_1 accuracy     4.0     1.0
task_2 accuracy     5.1     1.0
       precision    6.2     1.0

Seems you need to change res.total.task_2 value by updating all rows

res.total.task_2.iloc[:] = res.total.task_2 + update

Or with pandas.Series.update()

res.total.task_2.update(res.total.task_2 + update)

Or add value one by one

for i in range(len(update)):
    res.total.task_2.iloc[i] += update.iloc[i]
# print(res)

                  total  counts
task   metric                  
task_1 accuracy     4.0     1.0
task_2 accuracy     5.1     1.0
       precision    6.2     1.0

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