gpt4 book ai didi

python - Pandas 中的多行变成单行

转载 作者:行者123 更新时间:2023-12-05 01:49:47 25 4
gpt4 key购买 nike

我想展平(我不确定称它展平是否正确)带行的列。多行变成单行,列更改为 column_rows我有一个数据框如下:

data = {"a":[3,4,5,6],
"b":[88,77,66,55],
"c":["ts", "new", "thing", "here"],
"d":[9.1,9.2,9.0,8.4]}
df = pd.DataFrame(data)

我当前的输出是:

    a   b   c   d
0 3 88 ts 9.1
1 4 77 new 9.2
2 5 66 thing 9.0
3 6 55 here 8.4

我的预期输出:

    a_0  a_1 a_2 a_3 b_0 b_1 b_2 b_3 c_0 c_1 c_2 c_3 d_0 d_1 d_2 d_3
0 3 4 5 6 88 77 66 55 ts new thing here 9.1 9.2 9.0 8.4

从形状 (4,4) 到 (1, 16)

最佳答案

更新让我们使用 Python 3.8 中新增的 walrus operator 来创建单行代码:

(df_new := df.unstack().to_frame().T).set_axis(
[f"{i}_{j}" for i, j in df_new.columns], axis=1
)

输出:

  a_0 a_1 a_2 a_3 b_0 b_1 b_2 b_3 c_0  c_1    c_2   c_3  d_0  d_1  d_2  d_3
0 3 4 5 6 88 77 66 55 ts new thing here 9.1 9.2 9.0 8.4

试试这个,使用unstackto_frame 和转置。接下来,使用列表推导式展平列标题:

df_new = df.unstack().to_frame().T 
df_new.columns = [f'{i}_{j}' for i, j in df_new.columns]
df_new

输出:

  a_0 a_1 a_2 a_3 b_0 b_1 b_2 b_3 c_0  c_1    c_2   c_3  d_0  d_1  d_2  d_3
0 3 4 5 6 88 77 66 55 ts new thing here 9.1 9.2 9.0 8.4

关于python - Pandas 中的多行变成单行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73683616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com