【问题标题】:Convert pandas dataframe column to numpy array with each separated based on value in otehr column将 pandas 数据框列转换为 numpy 数组,每个数组根据另一列中的值分隔
【发布时间】:2020-07-03 11:14:37
【问题描述】:

我有一个带有两列的 pandas 数据框,例如:

data = {'first_column':  [1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 0.1, 0.2, 0.3, 0.4, 11, 12, 13],
        'second_column': [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3]
        }

df = pd.DataFrame (data, columns = ['first_column','second_column'])

我想得到一个像下面这样的 numpy 数组:

array([[[1.1], [2.1], [3.1], [4.1], [5.1], [6.1]], [[0.1], [0.2], [0.3], [0.4]], [[11], [12], [13]]])

我无法做到这一点。

【问题讨论】:

    标签: arrays python-3.x numpy list-comprehension numpy-ndarray


    【解决方案1】:

    这应该可以解决问题:

    df.groupby(['second_column']).apply(lambda x: list(map(lambda el:[el], x['first_column'].to_list()))).values
    

    我按您的第二列进行分组,并将每个组中的系列转换为列表。

    list(map(lambda el:[el],...))
    

    这部分将列表的每个元素转换为您在问题中提到的单个列表。

    【讨论】:

      【解决方案2】:

      使用聚合的一种方式:

      l = df.groupby("second_column")["first_column"].agg(list).tolist()
      print(l)
      

      输出:

      [[1.1, 2.1, 3.1, 4.1, 5.1, 6.1], [0.1, 0.2, 0.3, 0.4], [11.0, 12.0, 13.0]]
      

      【讨论】:

        猜你喜欢
        • 2019-02-25
        • 2019-03-08
        • 2016-03-31
        • 2017-11-09
        • 2020-06-20
        • 1970-01-01
        • 2021-06-05
        • 2020-02-20
        相关资源
        最近更新 更多