【问题标题】:Convert Pandas Series of 2D numpy arrays to Pandas DataFrame of columns of 1D numpy arrays将 Pandas 系列的二维 numpy 数组转换为一维 numpy 数组列的 Pandas DataFrame
【发布时间】:2019-05-05 07:18:43
【问题描述】:

第一次发布到 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) 的数组,所以我试图避免遍历行。

什么是有效的方法?

【问题讨论】:

    标签: python arrays pandas numpy dataframe


    【解决方案1】:

    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]
    

    【讨论】:

    • 这是一个不错的方法。作为一个迂腐点,每个单元格都包含一个列表而不是一个 numpy 数组。你可能想.applymap(np.array)
    • 您能详细说明一下吗? .applymap 在最终的 DF 上?
    • 如果你想用 numpy 数组代替列表,那么你可以使用df = df.applymap(np.array)
    【解决方案2】:

    您无需将最后一个维度转换为 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'>
    

    【讨论】:

      【解决方案3】:

      我会这样做:

      # 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]
      

      【讨论】:

        猜你喜欢
        • 2019-10-30
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 2021-04-04
        • 2021-09-25
        • 2019-03-12
        • 1970-01-01
        • 2018-12-27
        相关资源
        最近更新 更多