如何将普通数据帧转换为时间序列数据帧 [英] how to convert normal dataframe to time series dataframe

查看:40
本文介绍了如何将普通数据帧转换为时间序列数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有正常的数据框.

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

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

I would like convert to time series dataframe, could you teach me how to do?

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

In real dataset, there are a lot of cities. I want it automatically generating table.

我期望的时间序列是:

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

推荐答案

你可以使用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)

这篇关于如何将普通数据帧转换为时间序列数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆