gpt4 book ai didi

python - Pandas Plot 按时间分组的条形图

转载 作者:行者123 更新时间:2023-12-02 00:33:31 25 4
gpt4 key购买 nike

我在下面有一个表格,我想将其绘制成分组条形图。我希望 x 轴为 time_period,y 轴为 death_licenses,我希望按 civic_centre 分类。如您所见,对于每个不同的 time_periodcivic_centre 中都有四个分类选项。

+-------------+--------------+----------------+
| time_period | civic_centre | death_licenses |
+-------------+--------------+----------------+
| 2011-01-01 | ET | 410 |
| 2011-01-01 | NY | 681 |
| 2011-01-01 | SC | 674 |
| 2011-01-01 | TO | 297 |
| 2011-02-01 | ET | 307 |
| 2011-02-01 | NY | 388 |
| 2011-02-01 | SC | 407 |
| 2011-02-01 | TO | 223 |
| 2011-03-01 | ET | 349 |
| 2011-03-01 | NY | 655 |
| 2011-03-01 | SC | 400 |
| 2011-03-01 | TO | 185 |
| 2011-04-01 | ET | 373 |
| 2011-04-01 | NY | 640 |
| 2011-04-01 | SC | 457 |
| 2011-04-01 | TO | 42 |
+-------------+--------------+----------------+

这是我到目前为止所做的工作:

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

class Utility:

@staticmethod
def read_csv(csv, number_columns=[], categorical_columns=[], date_columns=[], drop_columns_if_empty=[], drop_duplicate_columns=[]):
df = pd.read_csv(csv, na_values=['--', ''])
df.rename(columns=lambda x: x.strip().replace('"', '').replace(' ', '_').replace('__', '_').lower(),
inplace=True)
df[number_columns] = df[number_columns].astype(str).replace({'[\$,)]': '', ' ': '', '[(]': '-'}, regex=True)
for col in number_columns:
df[col] = pd.to_numeric(df[col], errors='coerce')
for col in date_columns:
df[col] = pd.to_datetime(df[col], errors='coerce')

df.dropna(subset=drop_columns_if_empty, how='any', inplace=True)
df = df.applymap(lambda x: x.strip() if type(x) is str else x)
if (len(drop_duplicate_columns) > 1):
df = df.drop_duplicates(drop_duplicate_columns, keep='last')
for col in categorical_columns:
df[col] = pd.Categorical(df[col])

return df

df = Utility.read_csv('http://opendata.toronto.ca/clerk/registry.service/death.csv', number_columns=['death_licenses'], categorical_columns=['place_of_death', 'civic_centre'], date_columns=['time_period'])
df.sort_values(['time_period', 'civic_centre'], ascending=[True, False])
df2 = df.groupby(['time_period', 'civic_centre'])['death_licenses'].agg('sum').reset_index()

我想做这样的事情: grouped bar graph

最佳答案

这里有几个绘图选项(如果我没理解错的话),我自己更喜欢第一个。

% matplotlib inline

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

from pandas import Series, DataFrame

civics = ([i for i in ['ET', 'NY', 'SC', 'TO']] * 4)
civics.sort()

data = DataFrame({
'time_period': Series([pd.to_datetime('2011-0{}-01'.format(i)) for i in
range(1, 5)] * 4),
'civic_centre': Series(civics),
'death_licenses': Series(np.random.randint(400, 500, 16))
})

# As four series.

pd.pivot_table(data, index = 'time_period', columns = 'civic_centre', values
= 'death_licenses').plot();

# As a grouped bar plot.

pd.pivot_table(data, index = 'civic_centre', columns = 'time_period', values
= 'death_licenses').plot(kind = 'bar')

给出这两个图:

enter image description here

关于python - Pandas Plot 按时间分组的条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50789490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com