将Pandas Series中的2D numpy数组转换为Pandas DataFrame中的1D numpy数组列

4

这是我在stackoverflow上的第一篇帖子。我已经搜索了,但找不到答案。

我有一个Pandas系列,其中包含2D numpy数组:

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中一列中的1D numpy数组:
D应该长这样:
     0        1
a    [0,2,3]  [1,3,4]
b    [5,7,9]  [6,8,10]

请注意,我的实际数据集是1238500个大小为(32,8)的数组,因此我试图避免迭代行。
有什么高效的方法可以做到这一点?
3个回答

3

使用np.stackmap的一种解决方案

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]

1
这是一个不错的方法。作为一个严谨的观点,每个单元格包含一个列表而不是numpy数组。你可能想要使用.applymap(np.array) - hilberts_drinking_problem
你能详细说明一下吗?在最终的DF上使用.applymap方法? - R. Parker
如果您想使用numpy数组代替列表,则可以使用df = df.applymap(np.array) - Abhi

1
你可以在不将最后一个维度转换为Python列表的情况下进行拆分和压缩。
df = S.apply(np.split, args=[2, 1]).apply(pd.Series).applymap(np.squeeze)

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

args=[2, 1]中,2代表列数,1代表要切片的轴。
类型:
In [280]: df.applymap(type)
Out[280]: 
                         0                        1
a  <class 'numpy.ndarray'>  <class 'numpy.ndarray'>
b  <class 'numpy.ndarray'>  <class 'numpy.ndarray'>

0
我会像这样做:
# flatten the list
S = S.apply(lambda x: [i for s in x for i in s])

# pick alternate values and create a data frame
S = S.apply(lambda x: [x[::2], x[1::2]]).reset_index()[0].apply(pd.Series)

# name index
S.index = ['a','b']

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接