簡體   English   中英

將Pandas系列2D numpy數組轉換為1D numpy數組列的Pandas DataFrame

[英]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.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]

您可以拆分和擠壓,而無需將最后一個維度轉換為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM