无法创建仅包含熊猫DF特定列的Excel文件

时间:2020-07-01 15:42:18

标签: python excel pandas dataframe

url = 'https://data.cityofnewyork.us/api/views/25th-nujf/rows.csv'
baby_names = pd.read_csv(url)

girls = baby_names[baby_names['Gender'] == 'FEMALE']
boys = baby_names[baby_names['Gender'] == 'MALE']

excel_file = pd.ExcelWriter('Baby_Names.xlsx')

girls.to_excel(excel_file, sheet_name='Girls', index=False)
boys.to_excel(excel_file, sheet_name='Boys', index=False, columns=['Year of Birth', 'Gender', 'Ethnicity'])

excel_file.save()

第一页包含并且应该包含所有原始列,而第二页仅包含我提到的列。但是,最后这一行仍然包含所有原始列,仍然显示其他三列,好像我从未输入过columns=参数一样。

更新:此格式也不起作用:

with pd.ExcelWriter('Baby_Names.xlsx') as excel_file:
    girls.to_excel(excel_file, sheet_name='Girls', index=False)
    boys.to_excel(excel_file, sheet_name='Boys', index=False, columns=['Year of Birth', 'Gender', 'Ethnicity'])
    excel_file.save()

0 个答案:

没有答案