【问题标题】:Renaming a column in Pandas grouped By dataframe is failing重命名 Pandas 中按数据框分组的列失败
【发布时间】:2018-08-23 23:08:10
【问题描述】:

我有我的 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: 'state'

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.sort_values('state',ascending=False))
  • print(df_Done_Ccy_Grp.columns.tolist()) ['currency_str', 'state', 'Percentage']
  • @PeterLucas - 好的,输出正确。
  • @PeterLucas - 如果删除 level=0 还是同样的问题? df_Done_Ccy_Grp = df_Done_Ccy_Grp.rename(columns={'state':'Done Trades'}) ?
  • @PeterLucas - 另一个想法 - 也许在重命名之前检查输出数据帧,rename 之后的 display(df_Done_Ccy_Grp) 是什么?

标签: python pandas dataframe group-by rename


【解决方案1】:

重命名排序解决了这个问题:

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 

【讨论】:

    猜你喜欢
    • 2014-10-26
    • 2012-08-25
    • 2021-09-03
    • 2019-09-26
    • 2013-07-10
    • 1970-01-01
    • 2019-03-03
    • 2013-09-04
    • 2018-04-02
    相关资源
    最近更新 更多