0

I want to give names to call and concatenate the process data later.

from glob import glob
import nibabel as nib
import numpy as np

emot= glob('path/emotion_***.nii')

em_1 = nib.load(emot[0]).get_data()
em_2 = nib.load(emot[1]).get_data()

em_1 = np.reshape(em_1[:,36], (90,104))
em_2 = np.reshape(em_2[:,36], (90,104))

data_emot = np.concatenate([em_1,em_2])

How could I do it the faster way with more than 100 elements in the glob list?

Additional info, the nib.load() and .get_data() are the nibabel process. Thus, if they load together with numpy reshape, str is called, rather the loaded process.

Nufa
  • 122
  • 1
  • 11

1 Answers1

1

What about simply using a for-loop.

from glob import glob
import nibabel as nib
import numpy as np

emot = glob('path/emotion_***.nii')
to_concat = []

for el_i in emot:
    em_i = np.reshape(nib.load(el_i).get_data()[:,36], (90,104))
    to_concat.append(em_i)

So that you can concatenate the process data later.

data_emot = np.concatenate(to_concat)

To go further

Note that the for-loop above can be rewritten more compactly. As follows

to_concat = [np.reshape(nib.load(el_i).get_data()[:,36], (90,104))\
             for el_i in emot]

Or using the python-native map function

to_concat = map(lambda el_i:np.reshape(nib.load(el_i).get_data()[:,36], (90,104)),\
                emot)
Community
  • 1
  • 1
keepAlive
  • 6,369
  • 5
  • 24
  • 39
  • @Nufa. Also, if this answer has solved your question please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – keepAlive May 12 '17 at 02:37
  • FYI my comment does exactly the same but is written in a more compact, pythonic way using list comprehension. – Julien May 12 '17 at 02:45
  • @Julien. The OP does not seem to be at this level. Also, your code has a `SyntaxError`. – keepAlive May 12 '17 at 02:46
  • The OP should strive to be at this level ;), just copied and pasted OP's post, which had the syntax error already ;) – Julien May 12 '17 at 02:47
  • @Julien. I know what you did. Actually I first did just like you :) But you are right. I am going to add this to my answer. – keepAlive May 12 '17 at 02:48
  • actually this one does not work, because when it is trying to '.get_data()', the python gives and error that saying this is a string, 'AttributeError: 'str' object has no attribute 'get_data''. – Nufa May 12 '17 at 02:51
  • @Nufa. It works now. Check it. This `AttributeError` what due to the fact that the enclosing parenthesis of the function `nib.load()` was not placed correctly. – keepAlive May 12 '17 at 03:00
  • yup, it works now. Thank you. I've upped the answer. both. – Nufa May 12 '17 at 03:01