简体   繁体   中英

overwrite slice of multi-index dataframe with series

I have a multi-index dataframe and want to set a slice of one of its columns equal to a series, ordered (sorted) according to the column slice' and series' index-match. The column's innermost index and series' index are identical, except their ordering (sorting). (see example below)

I can do this by first sorting the series' index according to the column's index and then using series.values (see below), but this feels like a workaround and I was wondering if it's possible to directly assign the series to the column slice.

example:

    import pandas as pd
    multi_index=pd.MultiIndex.from_product([['a','b'],['x','y']])
    df=pd.DataFrame(0,multi_index,['p','q'])
    s1=pd.Series([1,2],['y','x'])
    df.loc['a','p']=s1[df.loc['a','p'].index].values

The code above gives the desired output, but I was wondering if the last line could be done simpler, eg:

    df.loc['a','p']=s1

but this sets the column slice to NaNs.

Desired output:

         p  q
    a x  2  0
      y  1  0
    b x  0  0
      y  0  0

obtained output from df.loc['a','p']=s1:

         p  q
    a x  NaN  0
      y  NaN  0
    b x  0.0  0
      y  0.0  0

It seems like a simple issue to me but I haven't been able to find the answer anywhere.

Have you tried something like that?

df.loc['a']['p'] = s1

Resulting df is here

     p  q
a x  2  0
  y  1  0
b x  0  0
  y  0  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