首页 > 解决方案 > 按性别和年份创建总出生数据的数据透视表,然后绘制它们

问题描述

我想按性别和年份创建总出生数据的数据透视表,然后绘制它们。

.csv 数据如下所示:

             name sex  births  year
0         Jessica   F   46459  1990
1          Ashley   F   45544  1990
2        Brittany   F   36532  1990
3          Amanda   F   34391  1990
4        Samantha   F   25864  1990
5           Sarah   F   25803  1990
6       Stephanie   F   24853  1990
7        Jennifer   F   22218  1990
8       Elizabeth   F   20739  1990
9          Lauren   F   20498  1990
10          Megan   F   20249  1990
11          Emily   F   19349  1990
12         Nicole   F   17948  1990
13          Kayla   F   17534  1990
14          Amber   F   15862  1990
15         Rachel   F   15692  1990
16       Courtney   F   15374  1990
17       Danielle   F   14330  1990
18        Heather   F   14216  1990
19        Melissa   F   13996  1990
20        Rebecca   F   13669  1990
21       Michelle   F   13408  1990
22        Tiffany   F   13160  1990
23        Chelsea   F   12782  1990
24      Christina   F   11924  1990
25      Katherine   F   11613  1990
26         Alyssa   F   11259  1990
27        Jasmine   F   11034  1990
28          Laura   F   10903  1990
29         Hannah   F   10276  1990
          ...  ..     ...   ...
587789      Ziyun   M       5  2009
587790     Zlatan   M       5  2009
587791       Zoen   M       5  2009
587792     Zubayr   M       5  2009
587793     Zuhaib   M       5  2009
587794      Zykee   M       5  2009
587795     Zykell   M       5  2009
587796      Zylar   M       5  2009
587797  Zyquarius   M       5  2009
587798      Zyran   M       5  2009
587799    Zyreion   M       5  2009
587800     Zyrian   M       5  2009
587801     Zyvion   M       5  2009

现在,有了这个文件,我需要完成任务。我需要创建正确的数据透视表并绘制它。

我试图用以下几行来做到这一点,但这是不正确的。

data = pd.read_csv('/file.csv',index_col = 'year', parse_dates=True)
print(data)

pivot = data.pivot_table(['births'], index=['sex','year'])

print(pivot)

fig1 = plt.figure()

ax1 = fig1.add_subplot(1, 1, 1)
ax1.plot(pivot['births'], linestyle="--", color="k", label="M")
ax1.plot(pivot['births'], linestyle="--", color="b", label="F")

ax1.tick_params(rotation=90)

标签: pythonpandasplotpivot

解决方案


推荐阅读