Fab*_*lls 3 python pivot-table dataframe pandas
我想将pandas df转换为One_hot pandas df.描述的最佳方式可能是一个例子:
我看起来像这样:
ID|DEV |STATE|
1 |DEV1|on
2 |DEV2|on
3 |DEV1|off
3 |DEV3|on
3 |DEV3|off
Run Code Online (Sandbox Code Playgroud)
我知道不唯一的ID并不好,我正在努力.
然后我转动桌子:
data.pivot_table(index='ID', columns=['DEV'], values='STATE', dropna=True, aggfunc='first')
Run Code Online (Sandbox Code Playgroud)
其结果如下
ID|DEV1|DEV2|DEV3
1 |on | NaN| NaN
2 | NaN| on | NaN
3 | off| NaN| on
4 | NaN| NaN| off
Run Code Online (Sandbox Code Playgroud)
我现在想得到这样的东西:
ID|DEV1.on|DEV1.off|DEV2.on|DEV3.on|DEV3.off
1 | 1 | 0| 0| 0| 0
2 | 0 | 0| 1| 0| 0
3 | 0 | 1| 0| 1| 0
4 | 0 | 0| 0| 0| 1
Run Code Online (Sandbox Code Playgroud)
我知道如何加入列名,但我不知道如何获得"一热"的样式.也许有可能使用aggfunc?
你能帮助我吗?
法比安
使用get_dummies带有分隔符的连接列.,逐ID列索引set_index和最后获取max每个索引:
df['join'] = df['DEV'] + '.' + df['STATE']
df = pd.get_dummies(df.set_index('ID')['join']).max(level=0)
print (df)
DEV1.off DEV1.on DEV2.on DEV3.off DEV3.on
ID
1 0 1 0 0 0
2 0 0 1 0 0
3 1 0 0 1 1
Run Code Online (Sandbox Code Playgroud)
另一个解决方案MultiIndex和重塑unstack- 然后是必要的swaplevel,sort_index并最后展平MultiIndex:
df = (pd.get_dummies(df.set_index(['ID','DEV'])['STATE'])
.max(level=[0,1])
.unstack(fill_value=0)
.swaplevel(0,1, axis=1)
.sort_index(axis=1))
df.columns = df.columns.map('.'.join)
print (df)
DEV1.off DEV1.on DEV2.off DEV2.on DEV3.off DEV3.on
ID
1 0 1 0 0 0 0
2 0 0 0 1 0 0
3 1 0 0 0 1 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
121 次 |
| 最近记录: |