I have normal dataframe.
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.
My expect time series is:
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
You can use 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
You can also use pd.crosstab(df.date, df.city)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.