gpt4 book ai didi

python - 将索引转换为列 - pandas

转载 作者:行者123 更新时间:2023-11-30 22:36:14 26 4
gpt4 key购买 nike

df=pd.DataFrame({'c1':[12,45,21,49],'c2':[67,86,28,55]})

我想将索引转换为列

c1            c2
0 1 2 3 0 1 2 3
12 45 21 49 67 86 28 55

我尝试结合 stackunstack 但到目前为止没有成功

最佳答案

使用unstack + to_frame + T :

df=pd.DataFrame({'c1':[12,45,21,49],'c2':[67,86,28,55]})
print (df.unstack().to_frame().T)
c1 c2
0 1 2 3 0 1 2 3
0 12 45 21 49 67 86 28 55

或者DataFrame + numpy.ravel + numpy.reshapeMultiIndex.from_product :

mux = pd.MultiIndex.from_product([df.columns, df.index])
print (pd.DataFrame(df.values.ravel().reshape(1, -1), columns=mux))
c1 c2 c3
0 1 2 3 0 1 2 3 0 1 2 3
0 12 67 67 45 86 86 21 28 28 49 55 55

关于python - 将索引转换为列 - pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44256915/

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