Python 熊猫将桌子旋转到1_热
我想把熊猫df转换成一只热熊猫df。 最好用一个例子来描述: 我拥有的df如下所示:Python 熊猫将桌子旋转到1_热,python,pandas,dataframe,pivot-table,Python,Pandas,Dataframe,Pivot Table,我想把熊猫df转换成一只热熊猫df。 最好用一个例子来描述: 我拥有的df如下所示: ID|DEV |STATE| 1 |DEV1|on 2 |DEV2|on 3 |DEV1|off 3 |DEV3|on 3 |DEV3|off ID|DEV1.on|DEV1.off|DEV2.on|DEV3.on|DEV3.off 1 | 1 | 0| 0| 0| 0 2 | 0 | 0| 1| 0| 0
ID|DEV |STATE|
1 |DEV1|on
2 |DEV2|on
3 |DEV1|off
3 |DEV3|on
3 |DEV3|off
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
我知道非唯一id不好,我正在努力
然后我旋转表格:
data.pivot_table(index='ID', columns=['DEV'], values='STATE', dropna=True, aggfunc='first')
其结果如下
ID|DEV1|DEV2|DEV3
1 |on | NaN| NaN
2 | NaN| on | NaN
3 | off| NaN| on
4 | NaN| NaN| off
我现在想得到这样的东西:
ID|DEV |STATE|
1 |DEV1|on
2 |DEV2|on
3 |DEV1|off
3 |DEV3|on
3 |DEV3|off
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
我知道如何加入列名,但我不知道如何获得“一个热门”样式。也许用aggfunc是可能的
你能帮我吗
Fabian与带分隔符的联接列一起使用
,按ID
索引列,按索引最后获取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
另一种解决方案是使用multi-index
并通过-进行重塑,但随后是必要的,最后是展平multi-index
:
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
另一种选择:
df['new_col'] = df['DEV'] + '.' + df['STATE']
df1 = pd.get_dummies(df['new_col'])
df = pd.concat([df, df1], axis=1).drop(['DEV', 'STATE','new_col'], axis=1)
df = df.groupby("ID").sum().replace(0, np.nan)
输出:
DEV1.off DEV1.on DEV2.on DEV3.off DEV3.on
ID
1 NaN 1.0 NaN NaN NaN
2 NaN NaN 1.0 NaN NaN
3 1.0 NaN NaN 1.0 1.0
非常感谢你!有没有一种方法可以使用
pd.get_dummies
并使用NaN而不是0?@FabianZills-Last adddf=df.mask(df==0)