我有以下数据。
idx Group key value Time IsTrue
1 bicycle person yes 9:30 yes
2 bicycle name bob 9:30 yes
3 bicycle alive yes 9:30 yes
5 non-cycle person no 1:30 no
6 non-cycle name jack 1:30 no 我想从dataframe得到以下结果
idx Group Time IsTrue person name alive
1 bicycle 9:30 yes yes bob yes
2 non-cycle 1:30 no no jack NA键列变成新列的地方,值是这些新列的行。其他所有行都有相同的值,但键列和值列除外。钥匙变了,所以我要做些有活力的事情。
我目前的解决方案使用了熊猫群&应用(基于group列),并为每个组创建了一个新的数据格式,但这似乎超出了工程化的范围。有更简单的解决办法吗?
发布于 2019-09-25 02:38:57
编辑
作为你的固定输出。我使用set_index和unstack添加了另一个解决方案
df.set_index(['Group', 'Time', 'IsTrue', 'key'])['value'].unstack().reset_index()
Out[503]:
key Group Time IsTrue alive name person
0 bicycle 9:30 yes yes bob yes
1 non-cycle 1:30 no NaN jack no原版:
你想要的输出令人困惑。如果这是你想要的,让我们试试这个解决方案。如果不是,我会删除它。
df.pivot_table(index=['Group', 'Time', 'IsTrue'], columns='key', values='value', aggfunc='first').reset_index()
Out[487]:
key Group Time IsTrue alive name person
0 bicycle 9:30 yes yes bob yes
1 non-cycle 1:30 no NaN jack no发布于 2019-09-25 02:49:23
在以下方面:
df = pd.read_clipboard()
pivot = df[['key', 'value', 'Group']].pivot(index='Group',columns='key').droplevel(0, axis=1).reset_index()
df.drop(['idx','key', 'value'], axis=1, inplace=True)
df = df.merge(pivot, on='Group').drop_duplicates().reset_index(drop=True)退出:
| | Group | Time | IsTrue | alive | name | person |
|---|-----------|------|--------|-------|------|--------|
| 0 | bicycle | 9:30 | yes | yes | bob | yes |
| 1 | non-cycle | 1:30 | no | NaN | jack | no |https://stackoverflow.com/questions/58090277
复制相似问题