[Python.NumPy] 텍스트 데이터를 읽기 저장하기 - np.loadtxt/np.savetxt/np.load/np.save

2020. 12. 14. 05:00Python과 머신러닝/NumPy 데이터 분석

1. np.loadtxt와 np.savetxt 예시 (텍스트 데이터 읽기 / 저장하기)

In [1]:import numpy as np
In [2]:a = np.loadtxt("./populations.txt", delimiter='\t') 
       a
Out[2]:array([[123., 234.], 
              [345., 456.], 
              [567., 678.]])

In [3]:a_int = a.astype(int) 
       a_int
Out[3]:array([[123, 234], 
              [345, 456], 
              [567, 678]])

In [4]:np.savetxt('int_data.csv', a_int, fmt='%.2e', delimiter=',')
  • np.loadtxt : 123~678이라는 값을 가진 populations.txt에서 tab으로 구분되어 있는 text 데이터를 읽어오는 함수이다.
  • delimiter란 데이터의 구분자가 tab이라는 것을 numpy에게 알려주어 parsing을 위한 정보를 제공하는 것이다.
  • np.savetext를 통해서  동일한 데이터를 format/delimiter를 지정하여 저장할 수 있다.
  • 이에 대한 결과는 본인 컴퓨터에서 직접 실행하여 확인해야 한다. (int_data.csv파일 생성 여부 확인)

 

2. NumPy object로 데이터 저장하고 읽기

In [5]:np.save('npy_test', arr=a_int)

In [6]:a_test = np.load(file="npy_test.npy") 
       a_test
Out[6]:array([[123, 234], 
              [345, 456], 
              [567, 678]])
              
In [7]:npy_array = np.load(file='npy_test.npy') 
       npy_array
Out[7]:array([[123, 234], 
              [345, 456], 
              [567, 678]])
  • np.save를 통해서 기존 array 데이터를 저장할 수 있다.
  • 이를 다시 불러오기 위해서는 np.load함수를 사용하면 된다.
반응형