3

I have a dataframe called data, a column of which contains strings. I want to extract the characters from the strings because my goal is to one-hot encode them and make the usable for classification. The column containing the strings is stored in predictors as follows:

predictors = pd.DataFrame(data, columns = ['Sequence']).to_numpy()

The result upon printing is:

[['DKWL']
 ['FCHN']
 ['KDQP']
 ...
 ['SGHC']
 ['KIGT']
 ['PGPT']]

,while my goal is to get somehing like:

[['D', 'K', 'W', 'L']
 ...
 ['P', 'G', 'P, 'T']]

which from my understanding is a more appropriate form for one-hot encoding.

I have already tried answers provided here How do I convert string characters into a list? or here How to create a list with the characters of a string? to no success.

Specifically, I also tried this:

for row in predictors:
    row = list(row)

but the result is in the same form as predictors, i.e.

 [['DKWL']
 ['FCHN']
 ['KDQP']
 ...
 ['SGHC']
 ['KIGT']
 ['PGPT']]
Nik
  • 35
  • 2
  • 6

1 Answers1

3

You can convert values to letters by list comprehension with list and then to array if necessary:

predictors = np.array([list(x) for x in data])

Or convert column predictors['Sequence']:

a = np.array([list(x) for x in predictors['Sequence']])
print(a)
[['D' 'K' 'W' 'L']
 ['F' 'C' 'H' 'N']
 ['K' 'D' 'Q' 'P']
 ['S' 'G' 'H' 'C']
 ['K' 'I' 'G' 'T']
 ['P' 'G' 'P' 'T']]

For Series use:

s = predictors['Sequence'].apply(list)
print(s)
0    [D, K, W, L]
1    [F, C, H, N]
2    [K, D, Q, P]
3    [S, G, H, C]
4    [K, I, G, T]
5    [P, G, P, T]
Name: Sequence, dtype: object
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252