[英]Renaming a column in Pandas grouped By dataframe is failing
我得到了groupby语句的结果:
df_Done_Ccy = df[
df['state'].str.contains('Done')
][['currency_str','state']]
d = {
('state',np.size) # apply the count of done trades to the following groupby
}
df_Done_Ccy_Grp = df_Done_Ccy.groupby('currency_str')['state'].agg(d).reset_index() #we reset the index and the old index is added as a column
df_Done_Ccy_Grp['Percentage'] = df_Done_Ccy_Grp['state'].div(df_Done_Ccy['state'].count())
print(df_Done_Ccy_Grp.columns)
display(df_Done_Ccy_Grp.sort_values('state',ascending=False))
Index(['currency_str', 'state', 'Percentage'], dtype='object')
currency_str state Percentage
7 USD 146 0.581673
9 ZAR 54 0.215139
3 EUR 24 0.095618
0 AUD 9 0.035857
4 GBP 7 0.027888
2 CAD 6 0.023904
5 NOK 2 0.007968
1 BRL 1 0.003984
6 SEK 1 0.003984
8 Und 1 0.003984
看起来不错,我只想将状态列重命名为“完成交易”。 重命名“ currency_str”或“ Percentage”时,以下行有效,但在“ state”(即KeyError)上失败:
df_Done_Ccy_Grp = df_Done_Ccy_Grp.rename(columns={'state':'Done Trades'}, level=0) # rename the column header in the groupby
导致此问题的数据框按列分组是什么? 还有另一种方法可以做到这一点吗?
彼得
对重命名进行排序可以解决此问题:
df_Done_Ccy_Grp = df_Done_Ccy_Grp.rename(columns={'state':'Done Trades'}, level=0)
display(df_Done_Ccy_Grp.sort_values('Done Trades',ascending=False)) – Peter Lucas
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.