Pandas中设置.to_string(index=False)仍显示索引的问题
问题解决:Pandas分组后去除索引显示
问题场景
用户有包含日期、姓名、水果、价格的表格,希望按年份分组展示数据,但编写的代码即使尝试使用to_string(index=False),输出仍保留索引。原代码如下:
import pandas as pd data=pd.read_excel("Book6.xlsx",sheet_name="Sheet6") df_new = data[['Date1','Name', 'Fruit','Price']] df_new['Date1'] = pd.to_datetime(df_new['Date1'], dayfirst=True, errors='coerce') result = df_new.reset_index().groupby([df_new['Date1'].dt.year,df_new['Name'],df_new['Fruit'],df_new['Price']]).agg('sum') print(result)#.to_string(index=False))
问题原因
原代码存在两处关键问题:
- 错误将
Price纳入分组键,导致价格无法被聚合,反而成为多层索引的一部分; - 误用
reset_index()将原数据索引加入聚合列,且分组结果以分组键作为多层索引,此时to_string(index=False)只能隐藏默认行索引,无法处理作为分组键的层级索引。
修正方案
方案1:分组后将索引转为列,再无索引输出
按年份、姓名、水果分组,对价格做聚合(以求和为例),再用reset_index()将分组索引转为普通列,最后输出时隐藏默认索引:
import pandas as pd data = pd.read_excel("Book6.xlsx", sheet_name="Sheet6") df_new = data[['Date1', 'Name', 'Fruit', 'Price']] df_new['Date1'] = pd.to_datetime(df_new['Date1'], dayfirst=True, errors='coerce') # 按年份、姓名、水果分组,对价格求和 result = df_new.groupby([df_new['Date1'].dt.year, 'Name', 'Fruit'])['Price'].sum().reset_index() # 可选:修改年份列名让表头更清晰 result.rename(columns={'Date1': 'Year'}, inplace=True) # 无索引输出 print(result.to_string(index=False))
方案2:分组时直接不保留索引(Pandas 1.1.0+支持)
使用groupby的as_index=False参数,让分组键直接以列的形式呈现,无需后续转索引操作:
import pandas as pd data = pd.read_excel("Book6.xlsx", sheet_name="Sheet6") df_new = data[['Date1', 'Name', 'Fruit', 'Price']] df_new['Date1'] = pd.to_datetime(df_new['Date1'], dayfirst=True, errors='coerce') # 用as_index=False让分组键作为列,而非索引 result = df_new.groupby([df_new['Date1'].dt.year, 'Name', 'Fruit'], as_index=False)['Price'].sum() result.rename(columns={'Date1': 'Year'}, inplace=True) print(result.to_string(index=False))
效果说明
修正后输出会以普通表格形式展示年份、姓名、水果、总价,无任何索引列,完全符合需求。
内容的提问来源于stack exchange,提问作者Gilly Kumar
相关产品推荐
相关产品推荐

