![](/img/trans.png)
[英]Creating a pandas dataframe from a 2d numpy array (to be a column of 1d numpy arrays) and a 1d np array of labels
[英]Convert Pandas Series of 2D numpy arrays to Pandas DataFrame of columns of 1D numpy arrays
第一篇文章到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)所以我试图避免迭代行。
有效的方法是什么?
一个使用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列表。
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'>
我想这样做:
# 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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.