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!

5
  • Cannot reproduce, can you provide a minimal reproducible example? Commented Nov 8, 2017 at 19:31
  • As an aside, why do you want an array of strings in the first place? Commented Nov 8, 2017 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. Commented Nov 8, 2017 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. Commented Nov 8, 2017 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... Commented Nov 8, 2017 at 22:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

What if you set dtype=object?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.