Home > Blockchain >  Convert numpy array to pandas dataframe with labels from list
Convert numpy array to pandas dataframe with labels from list

Time:12-21

please advice how to perform the following premutations:

array = [1, 3, 2] (numpy.ndarray)

l1 = ['foo_qwe1_ert1', 'bar_qwe2_ert2', 'baz_qwe3_ert3'] (list)

I need to get the following pandas dataframe:

Column1 Column2 Column3
foo qwe1 ert1
baz qwe3 ert3
bar qwe2 ert2

the problem is the list contains text labels from 0 to 30(format: XXX_YYY_ZZZ) and numpy.array has shape (3536,) and contains numbers from 0 to 30. I need to assign label for each number in array and save it as pandas dataframe

CodePudding user response:

First use DataFrame constructor with 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

And then change order by array by extract last integer from last column:

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

EDIT:

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')]

Or:

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

CodePudding user response:

You can just use:

df = pd.DataFrame(data={'list':['foo_qwe1_ert1', 'bar_qwe2_ert2', 'baz_qwe3_ert3']})
df[['Column1', 'Column2', 'Column3']] = df['list'].str.split('_', expand=True)
df.drop(columns=['list'], inplace=True)

OUTPUT:

  Column1 Column2 Column3
0     foo    qwe1    ert1
1     bar    qwe2    ert2
2     baz    qwe3    ert3

OR

l = ['foo_qwe1_ert1', 'bar_qwe2_ert2', 'baz_qwe3_ert3']
df = pd.DataFrame()
df[['Column1', 'Column2', 'Column3']] = pd.Series(l).str.split('_', expand=True)
print(df)

CodePudding user response:

You can use str.split and then reindex:

df = pd.Series(l1).str.split('_', expand=True)
df.index = [1,2,3]
df = df.reindex(array).reset_index(drop=True).rename(columns={i:'Column' str(i 1) for i in df.columns})

Output:

  Column1 Column2 Column3
0     foo    qwe1    ert1
1     baz    qwe3    ert3
2     bar    qwe2    ert2
  • Related