简体   繁体   中英

Pandas inserting rows in multiindex dataframe through loc no longer supported

I have a pandas dataframe like this:

pd.DataFrame.from_dict({(4.0,
  'Net Sales'): {('details',
   pd.Timestamp('2020-04-01 00:00:00'),
   'Apr_FY21'): 1000, ('details',
   pd.Timestamp('2020-05-01 00:00:00'),
   'May_FY21'): 1000, ('details',
   pd.Timestamp('2020-06-01 00:00:00'),
   'Jun_FY21'): 1000},
 (5.0,
  'Margin'): {('details',
   pd.Timestamp('2020-04-01 00:00:00'),
   'Apr_FY21'): 20, ('details',
   pd.Timestamp('2020-05-01 00:00:00'),
   'May_FY21'): 15, ('details',
   pd.Timestamp('2020-06-01 00:00:00'),
   'Jun_FY21'): 10}}).T

I want to add a calculated row which unfortunately is no longer supported through loc. What is the alternate?

 df2.loc[(5.1,'Margin %'),'details']=(np.divide(df2.loc[(5,'Margin)'),'details'],(df2.loc[(4,'Net Sales'),'details']))*100).values

KeyError: 'Passing list-likes to.loc or [] with any missing labels is no longer supported, see https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#deprecate-loc-reindex-listlike'

Create it as a Series and then append to the DataFrame:

s = pd.Series((np.divide(df2.loc[(5.0,'Margin'),'details'],(df2.loc[(4.0,'Net Sales'),'details']))*100).values, 
              index=df2.columns, 
              name = (5.1,'Margin %')
             )
df2 = df2.append(s)

You actually have a typo in your statement:

df.loc[(5.1,'Margin %'),'details']=(np.divide(df.loc[(5,'Margin)'),'details'],(df.loc[(4,'Net Sales'),'details']))*100).values

--------------------------------------------------------------------------------------------^

An extra ')' not needed

This does work:

 df2.loc[(5.1,'Margin %'),'details']=(np.divide(df2.loc[(5,'Margin'),'details'],(df2.loc[(4,'Net Sales'),'details']))*100).values

Output:

                 details                      
              2020-04-01 2020-05-01 2020-06-01
                Apr_FY21   May_FY21   Jun_FY21
4.0 Net Sales     1000.0     1000.0     1000.0
5.0 Margin          20.0       15.0       10.0
5.1 Margin %         2.0        1.5        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