python - 重新格式化/旋转 pandas 数据框

标签 python pandas dataframe

对于每一行,我希望将行的索引更改为 column_index,并将整个内容从 x 行 * y 列拆分为 1 行 * x*y 列形状。

import pandas as pd

df = pd.DataFrame(data=[['Jon', 21, 1.77,160],['Jane',44,1.6,130]],columns=['name','age', 'height','weight'])
want = pd.DataFrame(data=[['Jon', 21, 1.77,160,'Jane',44,1.6,130]],columns=['name_0','age_0', 'height_0','weight_0','name_1','age_1', 'height_1','weight_1'])

# original df
   name  age  height  weight
0   Jon   21    1.77     160
1  Jane   44    1.60     130

# desired df - want
  name_0  age_0  height_0  weight_0 name_1  age_1  height_1  weight_1
0    Jon     21      1.77       160   Jane     44       1.6       130

我尝试了df.unstack().to_frame().T,虽然它将行数减少到一,但它创建了一个多重索引,所以并不理想:

  name       age     height      weight     
     0     1   0   1      0    1      0    1
0  Jon  Jane  21  44   1.77  1.6    160  130

我认为数据透视表在这里不起作用。

最佳答案

使用stack并展平 MultiIndex:

out = df.stack().swaplevel().to_frame().T
out.columns = out.columns.map(lambda x: f'{x[0]}_{x[1]}')

输出:

  name_0 age_0 height_0 weight_0 name_1 age_1 height_1 weight_1
0    Jon    21     1.77      160   Jane    44      1.6      130

关于python - 重新格式化/旋转 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75827088/

相关文章:

Python Pandas : Vectorized operation bug?

python-3.x - 没有名为 'pandas' 的模块 - Jupyter、Python3 内核、TensorFlow 通过 Docker

python - Pandas.DataFrame.rename 方法中的参数 "index"是什么?

r - 从 R 中具有某些 NULL 值的对象创建数据框

python - tkinter CheckButton 中的 Textvariable

python - 如何在多个 Maya 网格中查找匹配顶点

python - 如何从 C++ 调用 Python

python - 如何使用运算符 'and' 和/或 'or' 映射两个过滤列表

python - 确定列值是否在基于另一列的条件范围之间

r - 如何使用 R 中的映射文件更改多个数据帧中的列名称?