E
Assuming that your dataframe is, for example, the following:df = pd.DataFrame(
data={
"year": [2018, 2018, 2019, 2019, 2019, 2019, 2020],
"country": ["ES", "ES", "DE", "DE", "UK", "DE", "UK"],
"title": ["A", "B", "A", "D", "C", "C", "C"],
}
)
df It would be like this: year country title
0 2018 ES A
1 2018 ES B
2 2019 DE A
3 2019 DE D
4 2019 UK C
5 2019 DE C
6 2020 UK C
To count the number of values title (or number of rows) by country and year, we do the following:df2 = pd.DataFrame(df.groupby(["country", "year"])["title"].count())
df2 It would be like this: title
country year
DE 2019 3
ES 2018 2
UK 2019 1
2020 1
To see the data better, we pivot df2:df3 = df2.pivot_table(values="title", index=["country"], columns=["year"],
fill_value=0)
df3 It would be like this:year 2018 2019 2020
country
DE 0 3 0
ES 2 0 0
UK 0 1 1
To count the number of values title (or number of rows) per country, we do the following:df4 = pd.DataFrame(df.groupby("country")["title"].count())
df4 It would be like this: title
country
DE 3
ES 2
UK 2
Finally, to count the number of values title (or number of rows) per year, we do the following:df5 = pd.DataFrame(df.groupby("year")["title"].count())
df5 It would be like this: title
year
2018 2
2019 4
2020 1