Please help me to re-form the data frame after counting the number of python data frames under certain conditions.

Asked 2 years ago, Updated 2 years ago, 79 views

df = pd.DataFrame([data])

The structure of the data table that comes out when you print df in is as follows.

The code is recorded for each date, and I'd like to distinguish how many codes 3 and how many codes 1 are for each day like the following picture. And with a line graph, the line of code 3 for every day And I'm going to draw a graph that represents code 1 every day, so what should I do with changing the data frame structure?

python pandas datetime dataframe

2022-09-20 21:45

2 Answers

https://stackoverflow.com/questions/39132742/groupby-value-counts-on-the-dataframe-pandas

>>> df = pd.DataFrame({"date":[ 505,505,505,506,506,506 ], "code":[3,3,1,3,2,1]})
>>> df
   date  code
0   505     3
1   505     3
2   505     1
3   506     3
4   506     2
5   506     1
>>> df_code_count_by_date = df.groupby(["date", "code"]).size().unstack(fill_value=0)
>>> df_code_count_by_date
code  1  2  3
date         
505   1  0  2
506   1  1  1
>>> print(df_code_count_by_date.to_markdown())
|   |   date |   1 |   2 |   3 |
|-------:|----:|----:|----:|
|    505 |   1 |   0 |   2 |
|    506 |   1 |   1 |   1 |


2022-09-20 21:45

I was thinking of a way to go down there.It seems better to use the unstack.

df = pd.DataFrame({"date":[ 505,505,505,506,506,506 ], "code":[3,3,1,3,2,1]})
df.pivot_table(index='date', columns='code', aggfunc='size', fill_value=0)

code    1   2   3
date            
505 1   0   2
506 1   1   1


2022-09-20 21:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.