1

I have some code that loops through files and grabs a datetime string and appends the string in each file to an empty list. I am trying to convert this list of strings into an array of strings:

timestamp=[]
line = open(filename).readlines()
lines = line[0::24]
for i in lines:
     time=i[7:27]
     timestamp.append(time)


timestamp=np.array(timestamp)

I get this error:

  ValueError: setting an array element with a sequence

The timestamp list looks like this:

[' 04/23/2014 00:00:00', ' 04/23/2014 00:10:00', ' 04/23/2014 00:20:00', ' 04/23/2014 00:30:00', ' 04/23/2014 00:40:00', ' 04/23/2014 00:50:00', ' 04/23/2014 01:00:00', ' 04/23/2014 01:10:00', ' 04/23/2014 01:20:00', ' 04/23/2014 01:30:00', ' 04/23/2014 01:40:00', ' 04/23/2014 01:50:00', ' 04/23/2014 02:00:00', ' 04/23/2014 02:10:00', ' 04/23/2014 02:20:00', ' 04/23/2014 02:30:00', ' 04/23/2014 02:40:00', ' 04/23/2014 02:50:00', ' 04/23/2014 03:00:00', ' 04/23/2014 03:10:00']

I am not sure why I can't turn this into an array so that I can write it to a column in a csv file with other arrays. This should be working so I am not sure why it wouldn't. Any ideas would be appreciated!

HM14
  • 689
  • 1
  • 10
  • 30
  • Cannot reproduce, can you provide a [mcve]? – juanpa.arrivillaga Nov 08 '17 at 19:31
  • As an aside, why do you want an *array* of strings in the first place? – juanpa.arrivillaga Nov 08 '17 at 19:31
  • I need to transpose the list so that I can write it out as a column in a .csv file where other arrays are also columns...would just be easier if the list of timestamps was an array as well so I can transpose it and add it to the csv file with the others that are arrays. – HM14 Nov 08 '17 at 21:20
  • We can't help you without seeing that `timestamp` list, preferable both in situation where it works and where it doesn't. – hpaulj Nov 08 '17 at 21:38
  • I can't get it to work at all now. I edited the post above with an update and the timestamp list... – HM14 Nov 08 '17 at 22:37

1 Answers1

0

A numpy.array is a homogeneous multidimensional array of objects that are the same type. It does not work the same as a Python list of lists which takes any type.

There is a great explanation of this here: How to assign a string value to an array in numpy?

If you really want to store strings then you need to set the dtype=str argument of your numpy array.

zerox1212
  • 166
  • 1
  • 7