我在 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
其中A
、B
等是顶级描述符,start
和end
是子描述符。后面的数字是成对的,A
、B
等的对数不同。观察 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]]
所需的输出是顶部的输出。它表示某个序列内子序列的起点和终点(A
,B
,C
是不同的序列)。根据序列本身,有不同数量的子序列满足我正在寻找的给定条件。因此,A
、B
等的 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/