如何重命名Pandas DataFrame首列?多种尝试均未成功
问题分析与解决方案
核心问题
你创建NewDf时,默认生成的列名是整数类型的0,而非字符串'0',所以用rename(columns={'0':'date'})无法匹配到目标列;另外部分修改操作未设置inplace=True或重新赋值,导致修改不生效。
修复步骤
1. 优化DataFrame创建(推荐)
直接在创建NewDf时指定列名,从根源避免列名修改问题:
def Walmart(data,stateAbb): # 将datebucket移到函数内部,避免多次调用累积数据 datebucket=[] Walmart_df=pd.DataFrame(data) Walmart_df=Walmart_df[Walmart_df['STRSTATE']== stateAbb] date=Walmart_df.sort_values(by='date_super').groupby(['STRSTATE','date_super'])['date_super'] test=date.first().index for i in test: datebucket.append(i[1]) cumsum=Walmart_df.groupby(['STRSTATE','date_super']).count()['storenum'] # 创建时直接指定列名为'date' NewDf=pd.DataFrame({'date': datebucket}, index=cumsum) NewDf.index.names = ['cumsum'] NewDf.dropna(inplace=True) display(NewDf) Walmart(df,'TX')
2. 修正原有rename操作
如果要保留原有创建逻辑,修改rename的匹配方式并确保修改生效:
def Walmart(data,stateAbb): datebucket=[] Walmart_df=pd.DataFrame(data) Walmart_df=Walmart_df[Walmart_df['STRSTATE']== stateAbb] date=Walmart_df.sort_values(by='date_super').groupby(['STRSTATE','date_super'])['date_super'] test=date.first().index for i in test: datebucket.append(i[1]) cumsum=Walmart_df.groupby(['STRSTATE','date_super']).count()['storenum'] NewDf=pd.DataFrame(datebucket,cumsum) NewDf.index.names = ['cumsum'] # 针对整数列名0进行修改,同时设置inplace=True NewDf.rename(columns={0:'date'}, inplace=True) # 或者直接替换列名(二选一即可) # NewDf.columns = ['date'] NewDf.dropna(inplace=True) display(NewDf) Walmart(df,'TX')
额外注意点
- 把
datebucket定义移到函数内部,避免多次调用Walmart函数时,列表累积之前的数据导致结果错误。 dropna()需要设置inplace=True或者重新赋值给NewDf(NewDf = NewDf.dropna()),否则不会删除缺失值。
内容的提问来源于stack exchange,提问作者Milan
相关产品推荐
相关产品推荐

