透视表和条形图

2024-10-05 17:39:40 发布

您现在位置:Python中文网/ 问答频道 /正文

Excel Pivot Output

Python Pivot Table

Python Pivot Chart

我想用Python提供同样的表格和图形输出。我尝试更改索引、列和值,但只得到如下错误:

  • 没有要聚合的数字类型
  • 位置参数跟在关键字参数后面
  • pivot_table()为参数“values”获取了多个值

我希望输出与excel的输出完全相同

文本形式的示例数据:

  columns: Transport Type, October, November, December, January, February, March, April, May, June, July, August, September

'Bus','63,438','90,027','40,584','9,497','90,252','65,717','684','21,344', '56,517','28,114','49,966','44,406'
'Bus','112,429','163,675','83,016','16,438','160,933','122,607','1,690','47,059','116,104','56,444','95,275','83,223' 

'Train','50,398','73,483','37,711','7,222','70,329','52,495','723','22,469', '60,685','33,011','55,747','52,311'
'Train','115,340','171,494','83,725','21,138','177,074','127,344','1,266', '50,432','134,814','75,109','129,841','125,747'

Tags: 文本图形类型参数错误tabletrain数字
1条回答
网友
1楼 · 发布于 2024-10-05 17:39:40

您可以将Seaborn的^{}long form中的数据一起使用:

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

sns.set()
columns= ['Transport Type', 'October', 'November', 'December', 'January', 'February', 'March', 'April',
          'May', 'June', 'July', 'August', 'September']
data =[['Bus','63,438','90,027','40,584','9,497','90,252','65,717','684','21,344','56,517','28,114','49,966','44,406'],
       ['Bus', '112,429','163,675','83,016','16,438','160,933','122,607','1,690','47,059','116,104','56,444','95,275','83,223'],
       ['Train','50,398','73,483','37,711','7,222','70,329','52,495','723','22,469','60,685','33,011','55,747','52,311'],
       ['Train','115,340','171,494','83,725','21,138','177,074','127,344','1,266','50,432','134,814','75,109','129,841','125,747']]
df = pd.DataFrame(data=data, columns=columns)
for col in columns[1:]:
    df[col] = pd.to_numeric(df[col].str.replace(',', ''))

table = pd.pivot_table(df, index='Transport Type', aggfunc=np.mean)

table_long = pd.melt(table.reset_index(), id_vars='Transport Type', var_name='Month', value_name='Mean')
ax = sns.barplot(data=table_long, x='Mean', y='Month',
                 orient='horizontal', hue='Transport Type', order=columns[1:])
ax.set_title('Student Usage')
ax.set_xlabel('Average Taps Ons & Offs')
plt.tight_layout()
plt.show()

example plot

PS:对于black background,您可以尝试:

sns.set(style="ticks", context="talk")
plt.style.use("dark_background")

相关问题 更多 >