[英]Pandas inserting rows in multiindex dataframe through loc no longer supported
I have a pandas dataframe like this:我有一个 pandas dataframe 像这样:
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.我想添加一个计算行,不幸的是,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' KeyError:'不再支持将 list-likes 传递给.loc 或带有任何缺失标签的 [],请参阅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:将其创建为一个系列,然后将 append 创建为 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: 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.