gpt4 book ai didi

python - 将二维 numpy 数组的 Pandas 系列转换为一维 numpy 数组列的 Pandas DataFrame

转载 作者:太空狗 更新时间:2023-10-30 02:52:19 24 4
gpt4 key购买 nike

第一次发布到 stackoverflow。我已经搜索过,但找不到答案。

我有一个二维 numpy 数组的 Pandas 系列:

import numpy as np
import pandas as pd

x1 = np.array([[0,1],[2,3],[3,4]],dtype=np.uint8)
x2 = np.array([[5,6],[7,8],[9,10]],dtype=np.uint8)

S = pd.Series(data=[x1,x2],index=['a','b'])

输出 S 应该是这样的:

a    [[0, 1], [2, 3], [3, 4]]
b [[5, 6], [7, 8], [9, 10]]

我希望将其转换为 Pandas DataFrame D,其中 S 中 2D numpy 数组的每一列都变成 D 列中的一维 numpy 数组:

D 应该是这样的:

     0        1
a [0,2,3] [1,3,4]
b [5,7,9] [6,8,10]

请注意,我的实际数据集是 1238500 个数组,大小为 (32,8),因此我试图避免遍历行。

执行此操作的有效方法是什么?

最佳答案

一种解决方案 np.stack map

df =  pd.DataFrame(np.stack(map(np.transpose, S)).tolist(), index=S.index)

print (df)

0 1
a [0, 2, 3] [1, 3, 4]
b [5, 7, 9] [6, 8, 10]

关于python - 将二维 numpy 数组的 Pandas 系列转换为一维 numpy 数组列的 Pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53603199/

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