python - Pandas Dataframe 用 stack 和 unstack 重塑
问题描述
我正在尝试弄乱熊猫堆栈和取消堆栈。我想知道是否有可能以这种方式重塑我的数据。
这是我正在练习的示例数据。
ID,Value1,Value2
1,3,12
1,4,13
1,5,14
1,6,15
1,7,16
2,8,17
2,9,18
2,10,19
2,11,20
我想以这种方式重塑。
ID
1 Index(Extra Column) Value1, value2
1 3 12
2 4 13
3 5 14
4 6 15
5 7 16
2
1 8 17
2 9 18
3 10 19
4 11 20
我试过这个
df1 = pd.DataFrame(df[['Value1', 'Value2']], index= df['ID']).stack()
或者
df1 = df.set_index(['ID']).stack()
这会将 Value1 和 Value2 从列更改为我不想要的行。
有任何想法吗 ?
解决方案
我在这里建议set_index
+ cumcount
:
df.set_index(['ID', df.groupby('ID').cumcount() + 1])
Value1 Value2
ID
1 1 3 12
2 4 13
3 5 14
4 6 15
5 7 16
2 1 8 17
2 9 18
3 10 19
4 11 20
另一种选择是使用concat
:
pd.concat({k : g.reset_index(drop=True) for k, g in df.drop('ID', 1).groupby(df.ID)})
Value1 Value2
1 0 3 12
1 4 13
2 5 14
3 6 15
4 7 16
2 0 8 17
1 9 18
2 10 19
3 11 20
推荐阅读
- javascript - 不了解递归的下一次迭代
- tableau-api - 处理变化数据的“Tableau”方式是什么?
- imap - 如果没有调用 ListMessages(),Aspose.Email.Clients.Imap.ImapClient FetchMessage 总是返回一个空/null MailMessage
- javascript - React callbackRef.current 不是函数
- javascript - Calling React/Webpack module code from Node
- css - Vuetify 没有 vue-cli sass/scss 冲突
- c++ - 部分覆盖文件描述符的内容
- python - 如何对多个列进行分组并在不同列上聚合差异?
- kotlin - Kotlin 解构声明:直接将解构值作为参数传递
- mediawiki - 了解维基媒体转储