如何将具有NumPy数组值的Pandas系列转换为数据框。

4
我有一个Pandas系列,其值是Numpy数组。为了简单起见,假设:
    series = pd.Series([np.array([1,2,3,4]), np.array([5,6,7,8]), np.array([9,10,11,12])], index=['file1', 'file2', 'file3'])
file1       [1, 2, 3, 4]
file2       [5, 6, 7, 8]
file3    [9, 10, 11, 12]

如何将其扩展为以下格式的数据框 df_concatenated
       0   1   2   3
file1  1   2   3   4
file2  5   6   7   8
file3  9  10  11  12

同一问题的更广泛版本。实际上,这个`series`是从一个不同形式的数据框中获得的:
DataFrame:
              0   1
file  slide        
file1 1       1   2
      2       3   4
file2 1       5   6
      2       7   8
file3 1       9  10
      2      11  12

通过按照“文件”索引分组,并将列连接起来。
   def concat_sublevel(data):
        return np.concatenate(data.values)

   series = data.groupby(level=[0]).apply(concat_sublevel)

也许有人能够从数据框 data 到达 df_concatenated 的更好的方法。
注意。对于不同的file值,slide子索引可能具有不同数量的值。在这种情况下,我需要重复其中一行以获得所有结果行中相同的维度。
1个回答

5
你可以尝试使用pandas Dataframe从records中获取数据。
pd.DataFrame.from_records(series.values,index=series.index)

输出:

    0   1   2   3
file1   1   2   3   4
file2   5   6   7   8
file3   9   10  11  12

2
等效替代方案:pd.DataFrame(series.values.tolist(), index=series.index) - jpp
太好了!谢谢。 - Olga Gorun

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