gpt4 book ai didi

python - 在没有 pd.pivot 的情况下从长到宽转换 Pandas 数据框

转载 作者:行者123 更新时间:2023-11-28 20:36:02 33 4
gpt4 key购买 nike

我有一个 pandas 数据框,如下所示:

df = pd.DataFrame([['joe', 21, 'M'], 
['jane', 22, 'F'],
['Alice', 34, 'F']],
columns=['name', 'age', 'sex'])

看起来像这样:

    name  age sex
0 joe 21 M
1 jane 22 F
2 Alice 34 F

这个数据框显然是一个 3x3 矩阵,我希望得到一个 1x9 矩阵,如下所示:

  name_1  age_1 sex_1 name_2  age_2 sex_2 name_3  age_3 sex_3
0 joe 21 M jane 22 F Alice 34 F

我不能使用“pivot”,因为我没有一列用作列,另一列用作值。我只是想移动我所有的行,使它们并排放置,我似乎无法全神贯注于如何以 pythonic 方式执行此操作。我是否只需要遍历行,将行附加到列表,将列表转换为数据框,然后重命名列?

最佳答案

选项 1
比较简单的版本

d = df.unstack()
d.index = d.index.map('{0[0]}_{0[1]}'.format)
d.to_frame().T

name_0 name_1 name_2 age_0 age_1 age_2 sex_0 sex_1 sex_2
0 joe jane Alice 21 22 34 M F F

选项 2
使事情复杂化但可能更快

from numpy.core.defchararray import add

cols = np.tile(df.columns.values, df.shape[0]).astype(str)
rows = np.arange(1, df.shape[0] + 1).repeat(df.shape[1]).astype(str)
vals = df.values.reshape(1, -1)
pd.DataFrame(vals, columns=add(cols, add('_', rows)))

name_1 age_1 sex_1 name_2 age_2 sex_2 name_3 age_3 sex_3
0 joe 21 M jane 22 F Alice 34 F

关于python - 在没有 pd.pivot 的情况下从长到宽转换 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45846657/

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