我有一个一级数据框:
d = {'A': np.random.randint(0, 10, 5)
, 'B': np.random.randint(0, 10, 5)
, 'C': np.random.randint(0, 10, 5)
, 'D': np.random.randint(0, 10, 5)}
x = pd.DataFrame(d)
print(x)
A B C D
0 8 7 6 0
1 6 5 4 9
2 4 0 5 7
3 1 9 7 9
4 6 9 9 8
此多级:
from functools import reduce
v = ['u','v','z']
l = ['300','350','400','450','500'] * len(v)
d = ['1','2','3','4'] * len(l)
size = len(v) * len(l) * len(d)
der_v = reduce(lambda x,y: x+y, [[i] * 20 for i in v])
der_l = reduce(lambda x,y: x+y, [[i] * 4 for i in l])
der_d = reduce(lambda x,y: x+y, [[i] for i in d])
arrays =[der_v,der_l,der_d]
y = pd.DataFrame(np.random.randint(0, 1, (5,60)),index=range(0,5), columns=arrays)
print(y)
u ... z
300 350 400 ... 400 450 500
1 2 3 4 1 2 3 4 1 2 ... 3 4 1 2 3 4 1 2 3 4
0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
2 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
3 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
4 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
[5 rows x 60 columns]
我正试图与之相伴:
z = pd.concat([x, y], axis=1)
所以,我是这样的:
A B C D (u, 300, 1) (u, 300, 2) (u, 300, 3) (u, 300, 4) \
0 8 7 6 0 0 0 0 0 ...
1 6 5 4 9 0 0 0 0 ...
2 4 0 5 7 0 0 0 0 ...
3 1 9 7 9 0 0 0 0 ...
4 6 9 9 8 0 0 0 0 ...
但是我得到了列作为元组,例如:(u,300,1)。有点奇怪! 在轴1上可以同时具有一个级别和多个级别吗?
预期输出:
u ... z
A B C D 300 350 400 ... 400 450 500
1 2 3 4 1 2 3 4 1 2 ... 3 4 1 2 3 4 1 2 3 4
0 8 7 6 0 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
1 6 5 4 9 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
2 4 0 5 7 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
3 1 9 7 9 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
4 6 9 9 8 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
我真的不知道是否可以将列分为一个级别和多个级别。因此,我希望可以切片。例如:y.loc [:,('u','500')]工作正常。但是确认后再也行不通了。
答案 0 :(得分:0)
我不进行串联求解,因为不可能在轴1中具有不同的级别。我决定使用数据框x中的数据作为数据框y中的索引。
因此,请按照以下步骤操作:
1。创建数据框x:
sel <- which(rowSums(m3T3L1mRNA.tmp[,c(2,4)] == 20) != 40)
2。基于数据框x创建索引:
d = {'A': np.random.randint(0, 10, 5)
, 'B': np.random.randint(0, 10, 5)
, 'C': np.random.randint(0, 10, 5)
, 'D': np.random.randint(0, 10, 5)}
x = pd.DataFrame(d)
A B C D
0 7 1 6 8
1 4 0 5 6
2 7 5 0 7
3 8 4 3 8
4 9 1 4 0
3。为数据框y创建框架:
index = [x[col] for col in x.columns]
4。现在,要创建数据框y,我们将x的索引用作参数:
from functools import reduce
v = ['u','v','z']
l = ['300','350','400','450','500'] * len(v)
d = ['1','2','3','4'] * len(l)
size = len(v) * len(l) * len(d)
der_v = reduce(lambda x,y: x+y, [[i] * 20 for i in v])
der_l = reduce(lambda x,y: x+y, [[i] * 4 for i in l])
der_d = reduce(lambda x,y: x+y, [[i] for i in d])
arrays =[der_v,der_l,der_d]