将numpy数组转换为带有列表标签的pandas数组

0pizxfdo  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(107)

请告知如何执行以下排列:

array = [1, 3, 2]  # numpy.ndarray

l1 = ['foo_qwe1_ert1', 'bar_qwe2_ert2', 'baz_qwe3_ert3']  # list

字符串
我需要得到以下的pandas框架:
| Column1| Column2| Column3|
| --|--|--|
| Foo| qwe1| ert 1|
| Baz| Qwe3| ert 3|
| 酒吧|Qwe2| ERT2|
问题是列表包含从0到30的文本标签(格式:XXX_YYY_ZZZ)和numpy。数组具有形状(3536,),并包含从0到30的数字。我需要为数组中的每个数字分配标签,并将其保存为pandas字符串

ff29svar

ff29svar1#

首先使用DataFrame构造函数和split

df = pd.DataFrame([x.split('_') for x in l1], columns=['Column1', 'Column2', 'Column3'])
print (df)
  Column1 Column2 Column3
0     foo    qwe1    ert1
1     bar    qwe2    ert2
2     baz    qwe3    ert3

字符串
然后通过从最后一列中提取最后一个整数来改变array的顺序:

df.index = df['Column3'].str.extract('(\d+)$', expand=False).astype(int)
df = df.loc[array].reset_index(drop=True)
print (df)
  Column1 Column2 Column3
0     foo    qwe1    ert1
1     baz    qwe3    ert3
2     bar    qwe2    ert2


编辑:

array = np.array([1, 3, 2])
l1 = ['foo_qwe1_ert1', 'bar_qwe2_ert2', 'baz_qwe3_ert3'] 

L = [x.split('_') for x in l1]
a, b, c = L[0]
b = b.replace('1','')
c = c.replace('1','')
print (b, c)
qwe ert

out = [(y[0], f'{b}{x}', f'{c}{x}') for x, y in zip(array, L)]
print (out)
[('foo', 'qwe1', 'ert1'), ('bar', 'qwe3', 'ert3'), ('baz', 'qwe2', 'ert2')]


或者:

out = [(y[0], f'qwe{x}', f'ert{x}') for x, y in zip(array, L)]
print (out)
[('foo', 'qwe1', 'ert1'), ('bar', 'qwe3', 'ert3'), ('baz', 'qwe2', 'ert2')]
df = pd.DataFrame(out, columns=['Column1', 'Column2', 'Column3'])
print (df)
  Column1 Column2 Column3
0     foo    qwe1    ert1
1     bar    qwe3    ert3
2     baz    qwe2    ert2

的字符串

相关问题