Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 save 2d array to file and load back
#1
I tried to save 2 dimensional array to a file and load it back. But not sure how to fix it. please advise. thanks.
import numpy as np
x = [['ABC', 123.45], ['DEF', 678.90]]
np.savetxt('text.txt',x)
y = np.loadtxt('text.txt')
Quote
#2
Default format string (fmt parameter) for the np.savetxt method coincide to floating point numbers, so, you need to change fmt to '%s' (strings):

import numpy as np
x = [['ABC', 123.45], ['DEF', 678.90]]
np.savetxt('text.txt', x, fmt='%s')

# default dtype for  np.loadtxt is also floating point, change it, to be able to load mixed data.
y = np.loadtxt('text.txt', dtype=np.object) 
Quote
#3
Is it a way to keep y same type (list) as x after loaded? Thanks.
Quote
#4
You can convert y to list using .tolist() method, e.g.

y = np.loadtxt('text.txt', dtype=np.object)
y = y.tolist()
Another way is to use standard pickle module.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  save my sensor data from the bme680 into a json or csv file Plastefuchs84 1 269 Aug-23-2019, 03:04 AM
Last Post: Plastefuchs84
  Is there a way to save a CSV file as a python object amjass12 4 256 Jul-16-2019, 12:00 PM
Last Post: amjass12
  Is there any way to properly load fixed width file into a dataframe using Pandas? vicky53 1 396 Mar-29-2019, 06:04 PM
Last Post: Larz60+
  Fatal Python error: initfsencoding: unable to load the file system codec gauravbhardwajee 11 7,892 Dec-03-2018, 08:29 PM
Last Post: gauravbhardwajee
  Load .abf file and for analysis with Pandas finalcode 0 527 Nov-10-2018, 09:51 AM
Last Post: finalcode
  loading a 3D array from a bin file Mark3232 1 740 May-04-2018, 11:36 AM
Last Post: j.crater
  Newbie, can't load csv file. david_ford 2 2,366 Apr-15-2018, 01:51 PM
Last Post: snippsat
  Send array of doubles to Python from C and back baptiste 7 2,349 Aug-18-2017, 07:03 AM
Last Post: baptiste
  access a very large file? As an array or as a dataframe? Angelika 5 1,875 May-18-2017, 08:15 AM
Last Post: Angelika

Forum Jump:


Users browsing this thread: 1 Guest(s)