在 Python 中处理分类数据
Kasey Jones
Research Data Scientist
adult = pd.read_csv("data/adult.csv")
adult1 = adult[adult["Above/Below 50k"] == " <=50K"]
adult2 = adult[adult["Above/Below 50k"] == " >50K"]
替换为
groupby_object = adult.groupby(by=["Above/Below 50k"])
groupby_object = adult.groupby(by=["Above/Below 50k"])
应用函数:
groupby_object.mean()
Age fnlgwt Education Num Capital Gain ...
Above/Below 50k
<=50K 36.783738 190340.86517 9.595065 148.752468 ...
>50K 44.249841 188005.00000 11.611657 4006.142456 ...
一行写法:
adult.groupby(by=["Above/Below 50k"]).mean()
选项 1:只对两列运行 .sum()。
adult.groupby(by=["Above/Below 50k"])['Age', 'Education Num'].sum()
Age Education Num
Above/Below 50k
<=50K 909294 237190
>50K 346963 91047
选项 2:对所有数值列运行 .sum(),再子集化。
adult.groupby(by=["Above/Below 50k"]).sum()[['Age', 'Education Num']]
优先选项 1——尤其在大数据集上。
adult.groupby(by=["Above/Below 50k", "Marital Status"]).size()
Above/Below 50k Marital Status
<=50K Divorced 3980
Married-AF-spouse 13
Married-civ-spouse 8284
Married-spouse-absent 384
Never-married 10192
Separated 959
Widowed 908
>50K Divorced 463
Married-AF-spouse 10 <--- 仅 10 条记录
Married-civ-spouse 6692
...
在 Python 中处理分类数据