Armin - 1 year ago 96

Python Question

I have an array which consists of two columns and several rows. IN the first column there are strings which I want to split. These elements have the form (*.txt).For instance, "main.txt", I need to save the prefix only (main). However, the "split" function does not work on an array. Can you tell me how can I address this problem?

I saw several posts similar to what I have asked, but I could not find my answer. Sorry for the inconveniences, in advance. I have just started using python.

Below, is my code and the error:

`arr = np.genfromtxt('file',dtype=(str))`

rest=arr.split(".")[0]AttributeError Traceback (most recent call last)

<ipython-input-27-02be1ad07338> in <module>()

----> 1 rest=arr.split(".")[0]

AttributeError: 'numpy.ndarray' object has no attribute 'split'

Answer Source

```
import numpy as np
x= np.array((('aa.txt',1),('b.tct',2)))
print np.apply_along_axis(lambda a: (a[0].split('.')[0],a[1]),1,x)
[['aa' '1']
['b' '2']]
```

EDIT: Perhaps I should elaborate - numpy arrays aren't natural for non numeric matrices. Consider lists (Assuming delimiter in file is space):

```
table=[(r.split()[0].split('.')[0],r.split()[1]) for r in open('file')]
```

or avoiding double split:

```
table = []
for r in open('file'):
r = r.split()
table.append((r[0].split('.')[0],r[1]))
```