python - 将 Pandas DataFrame 转换为单行 DataFrame,将一列的值保存为标题
问题描述
我有第一个数据框,我想将其转换为所需的数据框。我见过类似的问题,但我的问题有点复杂。
# My data frame
F,A,B,C,D,E
---------
Fo,1,2,3,4,5
Foo,6,7,8,9,10
Fooo,11,12,13,14,15
# my desirable data frame
A_Fo,B_Fo,C_Fo,D_Fo,E_Fo,A_Foo,B_Foo,C_Foo,D_Foo,E_Foo,A_Fooo,B_Fooo,C_Fooo,D_Fooo,E_Fooo
--------------------------
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
解决方案
Let us try this:
stacked = df.stack()
new_idx = list()
for l in stacked.index.levels[1]:
for f in stacked.index.levels[0]:
new_idx.append(l + '_' + f)
stacked.reset_index(drop=True, inplace=True)
stacked.index = new_idx
print(stacked.to_frame())
Output:
A_fo A_foo A_fooo B_fo B_foo B_fooo C_fo C_foo C_fooo D_fo D_foo D_fooo E_fo E_foo E_fooo
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
推荐阅读
- python - 如何在每行中显示分组变量计数
- javascript - 填充 Apache ECharts 行中的空白
- vba - 如何从 IE 切换到 XMLHTTP60
- c# - 从 Web 应用程序访问 Google 驱动器中的文件和文件夹
- python - 在 Gitlab CI 中为 Django 项目运行 Selenium 测试:ERR_CONNECTION_REFUSED on get live_server_url
- c - cs50 现金没有返回所需的输出
- xml - 为什么 xsl:for-each-group 缺少一些元素?
- azure - Azure DevOps 版本 - 如何在特定虚拟机上执行测试阶段?
- pandas - Pandas 数据框,从 groupby 中过滤掉值
- sharepoint - 使用 ngrok 将 SPFX WebPart 隧道传输到 BrowserStack