You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Pandas实现透视效果:统计作者的Fiction与Non Fiction作品数量并分列为展示

How to Split Fiction/Non-Fiction Counts into Separate Columns by Author

Hey there! I see the issue with your current approach—using value_counts() gives you a hierarchical index where Genre is part of the rows, but you want those genres as distinct columns. Let's fix this with a couple straightforward methods.

Method 1: Use pivot_table (Clean & Intuitive)

This is my go-to for this kind of reshaping, since it directly maps your desired rows/columns and aggregation:

import pandas as pd

# Assume your dataset is stored in a DataFrame called df
summary_table = df.pivot_table(
    index='Author ',  # Rows: Author names
    columns='Genre',  # Columns: Fiction/Non Fiction
    aggfunc='size',   # Count number of entries per group
    fill_value=0      # Fill 0 for authors missing one genre
)

# Clean up the output to make it a proper flat table
summary_table = summary_table.reset_index().rename_axis(None, axis=1)

print(summary_table)

Method 2: Modify Your Existing groupby Code

If you prefer building on what you already tried, just add unstack() to pivot the Genre levels into columns:

# Start with your grouping, then unstack Genre into columns
summary_table = df.groupby(['Author ', 'Genre']).size().unstack(fill_value=0)

# Same cleanup as above
summary_table = summary_table.reset_index().rename_axis(None, axis=1)

Example Output

Using your sample dataset, both methods will produce this clean table:

AuthorFictionNon Fiction
JJ Smith01
Jordan B. Peterson01
Stephen King10

Both approaches ensure you get the exact structure you need: one row per author, with separate columns for each genre's count.

内容的提问来源于stack exchange,提问作者Sahil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 14:32:34