python featureと関連数値（count, sum, avg, mean, median など）をcategorical variable に作成

ID, Feature, Feature_cnt -> Create Feature categorical variable

# Record Count 値が既に集計されている場合 ( sum() )

```python
import pandas as pd
df_s = pd.DataFrame( {"ID": ["A","A","B","B","C","C"], 
                      "Feature": [1,3,3,3,1,1],
                      "cnt": [1,2,1,1,4,2]} )
df_s
```

```python
#out
	ID	Feature	cnt
0	A	1	1
1	A	3	2
2	B	3	1
3	B	3	1
4	C	1	4
5	C	1	2
```

```python
df_s.Feature.unique().tolist()
#df_s.Feature.value_counts().index.tolist()
#df_s.Feature.value_counts(dropna=False).index.tolist()
```

```python
#out
[1, 3]
```

```python
sgb = df_s.cnt.groupby([df_s.ID, df_s.Feature])
type(sgb)
```

```python
#out
pandas.core.groupby.groupby.SeriesGroupBy
```

```python
sgb.head()
```

```python
#out
0    1
1    2
2    1
3    1
4    4
5    2
Name: cnt, dtype: int64
```

```python
sgb_sum = sgb.sum()
type(sgb_sum)
```

```python
#out
pandas.core.series.Series
```

```python
sgb_sum
```

```python
#out
ID  Feature
A   1          1
    3          2
B   3          2
C   1          6
Name: cnt, dtype: int64
```

```python
import numpy as np
sgb_sum_unstack = sgb_sum.unstack(fill_value=np.nan)
type(sgb_sum_unstack)
```

```python
#out
pandas.core.frame.DataFrame
```

```python
sgb_sum_unstack
```

```python
#out
Feature	1	3
ID		
A	1.0	2.0
B	NaN	2.0
C	6.0	NaN
```

```python
sgb_sum_unstack.columns
```

```python
#out
Int64Index([1, 3], dtype='int64', name='Feature')
```

```python
sgb_sum_unstack.columns = df_s.Feature.name + '_' + sgb_sum_unstack.columns.astype('str') + '_' + df_s.cnt.name
sgb_sum_unstack.columns
```

```python
#out
Index(['Feature_1_cnt', 'Feature_3_cnt'], dtype='object')
```

```python
sgb_sum_unstack
```

```python
#out
	Feature_1_cnt	Feature_3_cnt
ID		
A	1.0	2.0
B	NaN	2.0
C	6.0	NaN
```

```python
sgb_sum_unstack.div(sgb_sum_unstack.sum(axis=1), axis=0)
```

```python
#out
	Feature_1_cnt	Feature_3_cnt
ID		
A	0.333333	0.666667
B	NaN	1.000000
C	1.000000	NaN
```

# Record Count 値が集計されて無い場合 ( value_counts() )

```python
import pandas as pd
#df_s = pd.DataFrame( {"ID": ["A","A","A","B","B","C","C","C","C","C","C"], 
#                      "Feature": [1,3,3,3,3,1,1,1,1,1,1]} )
df_s = pd.DataFrame( 
       [["A",1],
        ["A",3],
        ["A",3],
        ["B",3],
        ["B",3],
        ["C",1],
        ["C",1],
        ["C",1],
        ["C",1],
        ["C",1],
        ["C",1]], 
       columns=["ID", "Feature"])
df_s
```

```python
#out
	ID	Feature
0	A	1
1	A	3
2	A	3
3	B	3
4	B	3
5	C	1
6	C	1
7	C	1
8	C	1
9	C	1
10	C	1
```

```python
sgb_valuecounts_unstack = df_s.Feature.groupby(df_s.ID).value_counts().unstack()
# sgb_valuecounts_unstack = df_s.groupby(["ID"])["Feature"].value_counts().unstack()
# sgb_valuecounts_unstack = df_s.groupby(df_s.ID).Feature.value_counts().unstack()

sgb_valuecounts_unstack
```

```python
#out
Feature	1	3
ID		
A	1.0	2.0
B	NaN	2.0
C	6.0	NaN
```

# Record数、平均、中央値 - count(), mean(), median()

```python
grouped = df_s.groupby(["ID"])["Feature"]
grouped.head(4)
```

```python
#out
0    1
1    3
2    3
3    3
4    3
5    1
6    1
7    1
8    1
Name: Feature, dtype: int64

```

```python
column_name = df_s.Feature.name
grp_cnt = grouped.count()
df_cnt = grp_cnt.to_frame(f'{column_name}_CNT')
df_cnt
```

```python
#out
	Feature_CNT
ID	
A	3
B	2
C	6
```

```python
grp_mean = grouped.mean()
df_mean = grp_mean.to_frame(f'{column_name}_AVG')
df_mean
```

```python
#out
	Feature_AVG
ID	
A	2.333333
B	3.000000
C	1.000000
```

```python
grp_median = grouped.median()
df_median = grp_median.to_frame(f'{column_name}_MED')
df_median
```

```python
#out
	Feature_MED
ID	
A	3
B	3
C	1
```

```python
df_join = (
    df_cnt
    .join(df_mean)
    .join(df_median)
)
df_join.head()
```

```python
#out

Feature_CNT	Feature_AVG	Feature_MED
ID			
A	3	2.333333	3
B	2	3.000000	3
C	6	1.000000	1
```