将Python中的交叉表导出到Excel – 我丢失了行索引/名称。

huangapple go评论85阅读模式
英文:

Exporting a Crosstab out of Python into Excel--I am losing my row indexes/names

问题

我正在编写一些代码,用于统计NBA球员在赛季中投进的三分球数量,按比赛累积计算。 (例如,扎克·拉文(Zach Lavine)曾经在一场比赛中投进11个三分球。这部分功能很好。 将Python中的交叉表导出到Excel – 我丢失了行索引/名称。

threes = pd.crosstab(df_subset['PLAYER_NAME'], df_subset['FG3M'])

问题是,当我将这个数据导出到Excel时,只看到了列,而不再看到与球员相关的行名称(索引)

threes.to_excel(r'C:\Users\three.xlsx', index=False, header=True)

将Python中的交叉表导出到Excel – 我丢失了行索引/名称。

我已经四处寻找答案并尝试通过谷歌搜索解决这个问题,但没有成功。 有人能帮忙吗? 有没有简单的方法来解决这个问题?

英文:

I am writing some code to count the number of three pointers an NBA player has made through the season, aggregated by game. (For example, Zach Lavine has had one game with 11 3-pointers made. That part works great. 将Python中的交叉表导出到Excel – 我丢失了行索引/名称。

threes=pd.crosstab(df_subset['PLAYER_NAME'], df_subset['FG3M'])

Problem is when I export this to excel I only see my columns and not the row names associated with players anymore (index)

threes.to_excel (r'C:\Users\three.xlsx', index = False, header=True)

将Python中的交叉表导出到Excel – 我丢失了行索引/名称。

I have looked around and tried googling my way out of this to no avail. Anyone help? Is there a simple way to fix this?

答案1

得分: 1

writer = pd.ExcelWriter('threes.xlsx', engine='xlsxwriter')
threes.reset_index().to_excel(writer, sheet_name='1', index=False)
writer.save()

This did the trick.

英文:
writer = pd.ExcelWriter('threes.xlsx', engine = 'xlsxwriter')
threes.reset_index().to_excel(writer,sheet_name = '1', index = False)
writer.save()

This did the trick.

将Python中的交叉表导出到Excel – 我丢失了行索引/名称。

huangapple
  • 本文由 发表于 2023年3月7日 09:22:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75657257.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定