题
我有一个数据框 untidy
attribute value
0 age 49
1 sex M
2 height 176
3 age 27
4 sex F
5 height 172
该'attribute'
列中的值会定期重复。所需的输出是tidy
age sex height
0 49 M 176
1 27 F 172
(行和列的顺序或其他标签无关紧要,我可以自己清理。)
实例化代码:
untidy = pd.DataFrame([['age', 49],['sex', 'M'],['height', 176],['age', 27],['sex', 'F'],['height', 172]], columns=['attribute', 'value'])
tidy = pd.DataFrame([[49, 'M', 176], [27, 'F', 172]], columns=['age', 'sex', 'height'])
尝试次数
这看起来像一个简单的枢轴操作,但是我的初始方法引入了NaN
值:
>>> untidy.pivot(columns='attribute', values='value')
attribute age height sex
0 49 NaN NaN
1 NaN NaN M
2 NaN 176 NaN
3 27 NaN NaN
4 NaN NaN F
5 NaN 172 NaN
一些混乱的尝试来解决此问题:
>>> untidy.pivot(columns='attribute', values='value').apply(lambda c: c.dropna().reset_index(drop=True))
attribute age height sex
0 49 176 M
1 27 172 F
>>> untidy.set_index([untidy.index//untidy['attribute'].nunique(), 'attribute']).unstack('attribute')
value
attribute age height sex
0 49 176 M
1 27 172 F
惯用的方法是什么?
使用pandas.pivot
与GroupBy.cumcount
新的索引值和rename_axis
用于删除列名:
df = pd.pivot(index=untidy.groupby('attribute').cumcount(),
columns=untidy['attribute'],
values=untidy['value']).rename_axis(None, axis=1)
print (df)
age height sex
0 49 176 M
1 27 172 F
另一个解决方案:
df = (untidy.set_index([untidy.groupby('attribute').cumcount(), 'attribute'])['value']
.unstack()
.rename_axis(None, axis=1))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句