【问题标题】:how to convert normal dataframe to time series dataframe如何将普通数据帧转换为时间序列数据帧
【发布时间】:2024-01-17 06:11:01
【问题描述】:

我有正常的数据框。

id  name    age city        date
1   Jane    43  London      2020-01-12
2   Jose    34  London      2020-01-12
3   Poul    53  Leed        2020-01-12
4   Mark    29  Manchester  2020-02-12
5   Zak     36  London      2020-02-12
6   Lin     75  Birmingham  2020-03-12
7   Word    55  York        2020-04-12
8   Gene    33  Leed        2020-04-12

我想转换成时间序列数据框,你能教我怎么做吗?

在真实数据集中,有很多城市。我希望它自动生成表格。

我期望的时间序列是:

date        London  Leed    Manchester  Birmingham  York    
2020-01-12  2       1       0           0            0
2020-02-12  1       0       1           0            0
2020-03-12  0       0       0           1            0
2020-04-12  0       1       0           0            1

【问题讨论】:

  • could you teach me how to do? 欢迎来到 SO。这不是讨论论坛或教程。请使用tour 并花时间阅读How to Ask 以及该页面上的其他链接。 Pandas 有 good documentation - 花一些时间来处理它。
  • 我认为这是一个很好的问题,但表述方式很糟糕。在这里以我认为更合适的形式提问:*.com/questions/65458681/…

标签: python dataframe time-series


【解决方案1】:

你可以使用pivot_table:

df.pivot_table(index='date', columns='city', aggfunc='size', fill_value=0)

city        Birmingham  Leed  London  Manchester  York
date
2020-01-12           0     1       2           0     0
2020-02-12           0     0       1           1     0
2020-03-12           1     0       0           0     0
2020-04-12           0     1       0           0     1

你也可以使用pd.crosstab(df.date, df.city)

【讨论】:

  • 你能分享如何绘制图形时间序列吗?
  • @Bella 见this