How to replace certain symbols in dtype.names in Python?

275 views Asked by At

I have a data file of the form given below:

column_1    column 2    column-3    column-4    column_5    column 6
1   2   3   1   2   3
4   3   2   3   2   4
1   4   3   1   4   3
5   6   4   5   6   4

When I import the following file the header names with spaces are automatically replaced by underscores which I replace back with spaces. But how to preserve the hyphens. The code I used is:

import numpy as np
with open('data.dat', 'rb') as f:
    header = f.readline().split('\t')
    arr = np.genfromtxt(f, names = header, comments='#', delimiter='\t', dtype=None)
arr.dtype.names = [j.replace('_', ' ').replace('-', ' ') for j in arr.dtype.names]
print arr.dtype.names

Output

('column_1', 'column_2', 'column3', 'column4', 'column_5', 'column_6')

How to get back the hyphens of column 3 and 4 in Python?

2

There are 2 answers

0
Bharadwaj On

Hint - you can use regex for extracting the data in the columns, for your above case the expression will look similar to this exp = r'column.\d'

0
farhawa On

Be sure that your headers are separated by \t in your file:

import numpy as np
with open('data.dat', 'rb') as f:
    header = f.read().split("\n")[0].split("\t")
    arr = np.genfromtxt(f, names = header,comments='#', delimiter='\t', dtype=object)
arr.dtype.names = [j.replace('_', ' ') if j[:-1]+"-"+j[-1] not in header else j[:-1]+"-"+j[-1] for j in arr.dtype.names]
print arr.dtype.names

>> ('column 1', 'column 2', 'column-3', 'column-4', 'column 5', 'column 6')