Kim
Kim

Reputation: 13

(pandas)I want add to count,percent at groupby

i do road csv file's and grouping 2 headers in csv file so i want to each other count about 1 headers value and percent count/total and add dataframe

have a lot of data in test.csv

==example==
country city   name
KOREA   busan  Kim
KOREA   busan  choi
KOREA   Seoul  park
USA     LA     Jane
Spain   Madrid Torres
(name is not overlap)
==========

csv_file = pd.read_csv("test.csv")
need_group = csv_file.groupby(['category','city names'])

returns

                               country                                   city names                                                  
0                              KOREA                                   Seoul, Busan, ...
1                              KOREA                                   Daegu, Seoul
2                              USA                                     LA, New York...
2                              USA                                     LA, ...

want to - count is cf name's

                               country                                 city names         count   percent                                               
0                              KOREA                                   Seoul                2       20%
1                              KOREA                                   Daegu                1       10%
2                              USA                                     LA                   2       20%
3                              USA                                     New York             1       10%
4                              Spain                                   Madrid               4       40%

Upvotes: 0

Views: 48

Answers (1)

jezrael
jezrael

Reputation: 862851

I believe you need counts per country and name by GroupBy.size and then percentage divide by length of DataFrame:

print (csv_file)
  country    city    name
0   KOREA   busan     Kim
1   KOREA   busan   Dongs
2   KOREA   Seoul    park
3     USA      LA    Jane
4   Spain  Madrid  Torres

df = csv_file.groupby(['country','city']).size().reset_index(name='count')
df['percent'] = df['count'].div(df['count'].sum()).mul(100)

Upvotes: 1

Related Questions