Python Pandas - reshape 数据框

标签 python pandas

给定以下数据框:

pd.DataFrame({"A":[1,2,3],"B":[4,5,6],"C":[6,7,8]})

   A   B   C
0  1   4   6
1  2   5   7
2  3   6   8
3  11  14  16
4  12  15  17
5  13  16  18

我想 reshape 它,使它看起来像这样:
   A   B   C   A_1   B_1   C_1   A_2   B_2   C_2
0  1   4   6     2     5     7     3     6     8
1  11  14  16    12    15    17    13    16    18

所以每3行分组为1行

我怎样才能用 Pandas 实现这一目标?

最佳答案

一种想法是使用整数和模除法创建 MultiIndex 并通过 DataFrame.unstack reshape :

a = np.arange(len(df))
df.index = [a // 3, a % 3]
df = df.unstack().sort_index(axis=1, level=1)
df.columns = [f'{a}_{b}' for a, b in df.columns]
print (df)
   A_0  B_0  C_0  A_1  B_1  C_1  A_2  B_2  C_2
0    1    4    6    2    5    7    3    6    8
1   11   14   16   12   15   17   13   16   18

对于反向操作,可以使用 str.split DataFrame.stack :
a = np.arange(len(df))
df1 = (df.set_index(pd.MultiIndex.from_arrays([a // 3, a % 3]))
         .unstack().sort_index(axis=1, level=1))
df1.columns = [f'{a}_{b}' for a, b in df1.columns]
print (df1)
   A_0  B_0  C_0  A_1  B_1  C_1  A_2  B_2  C_2
0    1    4    6    2    5    7    3    6    8
1   11   14   16   12   15   17   13   16   18
df1.columns = df1.columns.str.split('_', expand=True)
df2 = df1.stack().reset_index(drop=True)
print (df2)
    A   B   C
0   1   4   6
1   2   5   7
2   3   6   8
3  11  14  16
4  12  15  17
5  13  16  18

关于Python Pandas - reshape 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62245218/

相关文章:

python - 如何用代码更改Mayavi中的字体类型和大小?

pandas - 如果[Ticket]值(value)相同,但其中一项缺少Cabin值(value),请填写值(value)(泰坦尼克号)

python - 将列表转换为数据框中的不同列

python - Tornado 的非阻塞 ORM?

python - os.environ.get() 为 Heroku 环境变量返回 None

python - 如何将字符串转换为字典或列表?

python - Pandas DataFrame 中连续的 NaN 大于阈值

python - 如何将地理空间坐标 dataFrame 转换为原生 x,y 投影?

python - 值错误 : Mixing dicts with non-Series may lead to ambiguous ordering

python - 了解类类型 '__main__.ClassName'