Listing unique value counts per groups in pandas dataframe

白昼怎懂夜的黑 提交于 2020-01-24 19:32:09

问题


I am new to pandas and python.

I am trying to group items by one column and list the information from the data frame per group.

My dataframe:

        B          C        D          E              F
1       Honda      USA      2000       Washington     New
2       Honda      USA      2001       Salt Lake      Used
3       Ford       Canada   2005       Washington     New
4       Toyota     USA      2010       Ney York       Used
5       Honda      USA      2001       Salt Lake      Used
6       Honda      Canada   2011       Salt Lake      Crashed
7       Ford       Italy    2014       Rome           New

I am trying to group my dataframe by column B and list how many C, D, E, F column values are in group B. For example we see that in column B there are 4 Honda which I am grouping it together. Then I want to list the following information - USA(3), Canada(1), 2000(1),2001(2), 2011(1), Washington(1), Salt Lake(3), New(1), Used(2), Crashed(1) and do the same per every group ( car make ) in column B:

        Car         Country        Year        City             Condition
1       Honda(4)    USA(3)         2000(1)     Washington(1)    New(1)
                    Canada(1)      2001(2)     Salt Lake(3)     Used(2)
                                   2011(1)                      Crashed(1)

2       Ford(2)     Canada(1)      2005(5)     Washington(1)    New(2)
                    Italy(1)       2014(1)     Rome(1)

...

What I've tried so far:

df.groupby(['B'])

Which gives me back <pandas.core.groupby.generic.DataFrameGroupBy object at 0x11d559080>

At this point, I am not sure how I should code moving on forward getting the desired results after grouping the column B.

Thank you for your suggestions.


回答1:


You need lambda function with custom function for processing each column separately with Series.value_counts and then join values of index to values of counts of Series together:

def f(x):
    x = x.value_counts()
    y = x.index.astype(str) + '(' + x.astype(str) + ')'
    return y.reset_index(drop=True)
df1 = df.groupby(['B']).apply(lambda x: x.apply(f)).reset_index(drop=True)
print (df1)
           B          C        D              E           F
0    Ford(2)   Italy(1)  2014(1)  Washington(1)      New(2)
1        NaN  Canada(1)  2005(1)        Rome(1)         NaN
2   Honda(4)     USA(3)  2001(2)   Salt Lake(3)     Used(2)
3        NaN  Canada(1)  2011(1)  Washington(1)  Crashed(1)
4        NaN        NaN  2000(1)            NaN      New(1)
5  Toyota(1)     USA(1)  2010(1)    Ney York(1)     Used(1)


来源:https://stackoverflow.com/questions/59542245/listing-unique-value-counts-per-groups-in-pandas-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!