python - 构建 3D Pandas DataFrame

标签 python pandas

我在 Pandas 中构建 3D DataFrame 时遇到困难。我想要这样的东西

A               B               C
start    end    start    end    start    end ...
7        20     42       52     90       101
11       21                     213      34
56       74                     9        45
45       12

其中AB等是顶级描述符,startend是子描述符。后面的数字是成对的,AB 等的对数不同。观察 A 有四个这样的对,B只有1个,C有3个。

我不确定如何继续构建此 DataFrame。修改this示例没有给我设计的输出:

import numpy as np
import pandas as pd

A = np.array(['one', 'one', 'two', 'two', 'three', 'three'])
B = np.array(['start', 'end']*3)
C = [np.random.randint(10, 99, 6)]*6
df = pd.DataFrame(zip(A, B, C), columns=['A', 'B', 'C'])
df.set_index(['A', 'B'], inplace=True)
df

成功:

                C
 A          B   
 one        start   [22, 19, 16, 20, 63, 54]
              end   [22, 19, 16, 20, 63, 54]
 two        start   [22, 19, 16, 20, 63, 54]
              end   [22, 19, 16, 20, 63, 54]
 three      start   [22, 19, 16, 20, 63, 54]
              end   [22, 19, 16, 20, 63, 54]

有什么方法可以将 C 中的列表分解为它们自己的列?

编辑:我的 C 的结构很重要。如下所示:

 C = [[7,11,56,45], [20,21,74,12], [42], [52], [90,213,9], [101, 34, 45]]

所需的输出是顶部的输出。它表示某个序列内子序列的起点和终点(ABC是不同的序列)。根据序列本身,有不同数量的子序列满足我正在寻找的给定条件。因此,AB 等的 start:end 对的数量不同

最佳答案

首先,我认为你需要填写 C 来表示缺失值

In [341]: max_len = max(len(sublist) for sublist in C)
In [344]: for sublist in C:
     ...:     sublist.extend([np.nan] * (max_len - len(sublist)))

In [345]: C
Out[345]: 
[[7, 11, 56, 45],
 [20, 21, 74, 12],
 [42, nan, nan, nan],
 [52, nan, nan, nan],
 [90, 213, 9, nan],
 [101, 34, 45, nan]]

然后,转换为 numpy 数组,转置,并与列一起传递给 DataFrame 构造函数。

In [288]: C = np.array(C)
In [289]: df = pd.DataFrame(data=C.T, columns=pd.MultiIndex.from_tuples(zip(A,B)))

In [349]: df
Out[349]: 
     one         two       three     
   start  end  start  end  start  end
0      7   20     42   52     90  101
1     11   21    NaN  NaN    213   34
2     56   74    NaN  NaN      9   45
3     45   12    NaN  NaN    NaN  NaN

关于python - 构建 3D Pandas DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24290495/

相关文章:

python - Pandas 分组并做总结

python - 加快 Pandas 数据框中的搜索速度

python - 如何使用管理员在 Python 中运行 cmd 命令

python - 在 Dask 中预先分散数据对象是否有优势?

python - 有没有办法根据与 Pandas 中另一列关联的值来填充列?

python - 在 Python/Pandas 中连接/合并数据框和编辑列名

python - 循环遍历行以应用函数 - Python

python - 在 Django 中更改使用 ModelForm 创建的表单元素的宽度

python - 如何从 asyncio 中的信号处理程序捕获自定义异常?

python - os.walk 返回一个生成器对象。我究竟做错了什么?