简体   繁体   中英

Setting a pandas sub dataframe indexed with a MultiIndex

I have a pandas.DataFrame with a Multi such as:

In [298]: pd.DataFrame(index=pd.MultiIndex.from_tuples([['a', 1], ['a', 2], ['b', 1], ['b', 3]]), data={'x': 1})
Out[298]: 
     x
a 1  1
  2  1
b 1  1
  3  1

When i want to reassign a sub dataframe ie ( df.loc['a'] ), i get a weird output:

In [300]: df.loc['a'] = df.loc['a']

In [301]: df
Out[301]: 
      x
a 1 NaN
  2 NaN
b 1   1
  3   1

The example is simple, i obviously intent to have a reassignment more complicated.

Is it normal? How can i reassign a sub dataframe indexed with a MultiIndex?

You can use [[..]] (update the DataFrame rather than the Series):

In [11]: df
Out[11]:
     x
a 1  1
  2  1
b 1  1
  3  1

In [12]: df2 = pd.DataFrame(index=pd.MultiIndex.from_tuples([['a', 1], ['a', 2], ['b', 1], ['b', 3]]), data={'x': 2})

In [13]: df.loc[["a"]] = df2.loc[["a"]]

In [14]: df
Out[14]:
     x
a 1  2
  2  2
b 1  1
  3  1

You can use pd.IndexSlice to represent slices of a pd.MultiIndex

df.loc[pd.IndexSlice['a', :], :] = 2
print df

a 1  2
  2  2
b 1  1
  3  1

Other examples

df = pd.DataFrame(index=pd.MultiIndex.from_tuples([['a', 1], ['a', 2], ['b', 1], ['b', 3]]), data={'x': 1})

df.loc[pd.IndexSlice[:, 1], :] = 9

print df

     x
a 1  9
  2  1
b 1  9
  3  1

Or

df = pd.DataFrame(index=pd.MultiIndex.from_tuples([['a', 1], ['a', 2], ['b', 1], ['b', 3]]), data={'x': 1})

df.loc[pd.IndexSlice['b', 3], :] = 31415

print df

         x
a 1      1
  2      1
b 1      1
  3  31415

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