我有一组样本数据
STATE CAPSULES LIQUID TABLETS
Alabama NaN Prescription OTC
Georgia Prescription NaN OTC
Texas OTC OTC NaN
Texas Prescription NaN NaN
Florida NaN Prescription OTC
Georgia OTC Prescription Prescription
Texas Prescription NaN OTC
Alabama NaN OTC OTC
Georgia OTC NaN NaN
我尝试了多种 groupby 配置,以获得以下理想结果:
State capsules_OTC capsules_prescription liquid_OTC liquid_prescription tablets_OTC tablets_prescription
Alabama 0 0 0 0 0 0
Florida 0 0 0 0 0 0
Georgia 1 1 1 1 1 1
Texas 1 2 2 2 2 2
例如,尝试了这个:
df.groupby(['STATE','CAPSULES'])
尝试至少整理第一列,但没有成功。也许这不是一个简单的答案,但我想我在groupby和count()或其他apply函数方面错过了一些简单的东西?
pd.get_dummies(df, columns=['CAPSULES', 'LIQUID', 'TABLETS']).sum(level='STATE')
- Erfan