在向datafram追加总计行之后删除pandas dataframe索引的名称

2024-10-01 17:31:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我计算了一系列一周中每天的总计提示,并将其添加到totalspt数据帧的底部。在

我已经将totalspt数据帧的index.name设置为None。在

但是,当dataframe显示默认的0,1,2,3索引时,它不会在索引正上方的左上角显示默认的空单元格。在

我怎样才能在数据帧中使这个单元格为空?在

enter image description here

   total_bill   tip sex smoker  day time  size   tip_pct
0       16.54  1.01   F      N  Sun    D     2  0.061884
1       12.54  1.40   F      N  Mon    D     2  0.111643
2       10.34  3.50   M      Y  Tue    L     4  0.338491
3       20.25  2.50   M      Y  Wed    D     2  0.123457
4       16.54  1.01   M      Y  Thu    D     1  0.061064
5       12.54  1.40   F      N  Fri    L     2  0.111643
6       10.34  3.50   F      Y  Sat    D     3  0.338491
7       23.25  2.10   M      Y  Sun    B     3  0.090323

pivot  =  tips.pivot_table('total_bill', index=['sex', 'size'],columns=['day'],aggfunc='sum').fillna(0)
print pivot
day         Fri    Mon    Sat    Sun    Thu    Tue    Wed
sex size
F   2     12.54  12.54   0.00  16.54   0.00   0.00   0.00
    3      0.00   0.00  10.34   0.00   0.00   0.00   0.00
M   1      0.00   0.00   0.00   0.00  16.54   0.00   0.00
    2      0.00   0.00   0.00   0.00   0.00   0.00  20.25
    3      0.00   0.00   0.00  23.25   0.00   0.00   0.00
    4      0.00   0.00   0.00   0.00   0.00  10.34   0.00

totals_row  =  tips.pivot_table('total_bill',columns=['day'],aggfunc='sum').fillna(0).astype('float')
totalpt  = pivot.reset_index('sex').reset_index('size')
totalpt.index.name = None
totalpt = totalpt[['Fri', 'Mon','Sat', 'Sun', 'Thu', 'Tue', 'Wed']]
totalpt = totalpt.append(totals_row)
print totalpt
**day**              Fri    Mon    Sat    Sun    Thu    Tue    Wed #problem text day 
0           12.54  12.54   0.00  16.54   0.00   0.00   0.00
1            0.00   0.00  10.34   0.00   0.00   0.00   0.00
2            0.00   0.00   0.00   0.00  16.54   0.00   0.00
3            0.00   0.00   0.00   0.00   0.00   0.00  20.25
4            0.00   0.00   0.00  23.25   0.00   0.00   0.00
5            0.00   0.00   0.00   0.00   0.00  10.34   0.00
total_bill  12.54  12.54  10.34  39.79  16.54  10.34  20.25

Tags: sizeindexsattotalsunpivotdaybill
2条回答

这是列的名字。在

In [11]: df = pd.DataFrame([[1, 2]], columns=['A', 'B'])

In [12]: df
Out[12]:
   A  B
0  1  2

In [13]: df.columns.name = 'XX'

In [14]: df
Out[14]:
XX  A  B
0   1  2

您可以将其设置为“无”以清除它。在

^{pr2}$

如果您想保留它,另一种方法是为索引命名:

In [21]: df.columns.name = "XX"

In [22]: df.index.name = "index"

In [23]: df
Out[23]:
XX     A  B
index
0      1  2

您可以使用rename_axis。自从0.17.0

In [3939]: df
Out[3939]:
XX  A  B
0   1  2

In [3940]: df.rename_axis(None, axis=1)
Out[3940]:
   A  B
0  1  2

In [3942]: df = df.rename_axis(None, axis=1)

In [3943]: df
Out[3943]:
   A  B
0  1  2

相关问题 更多 >

    热门问题