位置参数与python中的数据透视表不匹配

时间:2019-04-17 06:00:11

标签: python pandas

我的数据框看起来像-

id amt数量m_status年龄c_desc存在 1 95.00 1已婚36.0其他1 1 39.00 1已婚36.0其他1 2 72.00 2单身30.0南0 2 32.00 5单身30.0其他0 3 267.61 4已婚61.0其他0 4 594.00 1单人51.0南1 4 550.00 5单身51.0南1

我希望我的最终数据框应该是-

id南其他 1 0 2 2 2 5 3 0 4 4 6 0

我已经完成了代码。但是出现了这个错误-

TypeError                                 Traceback (most recent call last)
<ipython-input-30-56167b862c95> in <module>
      1 x = final_df_1.pivot_table(index=['id'], 
      2                      columns ='c_desc', values='qty', aggfunc='sum')
----> 3 total_qty_spend = x.reset_index().rename_axis(None,1)

/mnt/var/anaconda3/lib/python3.6/site-packages/pandas/util/_decorators.py in wrapper(*args, **kwargs)
    195         @wraps(func)
    196         def wrapper(*args, **kwargs):
--> 197             return func(*args, **kwargs)
    198 
    199         if not PY2:

TypeError: rename_axis() takes from 1 to 2 positional arguments but 3 were given

我的代码是-

final_df_1 = pd.read_csv('data.csv')

    x = final_df_1.pivot_table(index=['id'], 
                         columns ='c_desc', values='qty', aggfunc='sum')
    total_qty_spend = x.reset_index().rename_axis(None,1)
    total_qty_spend.fillna(0,inplace = True)

    total_qty_spend.head()

1 个答案:

答案 0 :(得分:0)

添加axis=1代替1,还可以将参数fill_value=0添加到DataFrame.pivot_table,以替换由透视操作创建的缺失值:

total_qty_spend = x.reset_index().rename_axis(None,axis=1)

一起:

x = final_df_1.pivot_table(index=['id'], 
                           columns ='c_desc', 
                           values='qty', 
                           aggfunc='sum',
                           fill_value=0)

total_qty_spend = x.reset_index().rename_axis(None,axis=1)
print (total_qty_spend)
   id  South  others
0   1      0       2
1   2      2       5
2   3      0       4
3   4      6       0