Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numpy, list or float to string in python

Tags:

python

numpy

I'm writing a python function to append data to text file, as shown in the following,

The problem is the variable, var, could be a 1D numpy array, a 1D list, or just a float number, I know how to convert numpy.array/list/float to string separately (meaning given the type), but is there a method to convert var to string without knowing its type?

def append_txt(filename, var):
    my_str = _____    # convert var to string
    with open(filename,'a') as f:
        f.write(my_str + '\n')

Edit 1: Thanks for the comments, sorry maybe my question was not clear enough. str(var) on numpy would give something like []. For example, var = np.ones((1,3)), str(var) will give [[1. 1. 1.]], and [] is unwanted,

Edit 2: Since I want to write clean numbers (meaning no [ or ]), it seems type checking is inevitable.

like image 640
jw21 Avatar asked Mar 18 '23 23:03

jw21


2 Answers

Type checking is not the only option to do what you want, but definitely one of the easiest:

import numpy as np

def to_str(var):
    if type(var) is list:
        return str(var)[1:-1] # list
    if type(var) is np.ndarray:
        try:
            return str(list(var[0]))[1:-1] # numpy 1D array
        except TypeError:
            return str(list(var))[1:-1] # numpy sequence
    return str(var) # everything else

EDIT: Another easy way, which does not use type checking (thanks to jtaylor for giving me that idea), is to convert everything into the same type (np.array) and then convert it to a string:

import numpy as np

def to_str(var):
    return str(list(np.reshape(np.asarray(var), (1, np.size(var)))[0]))[1:-1]

Example use (both methods give same results):

>>> to_str(1.) #float
'1.0'
>>> to_str([1., 1., 1.]) #list
'1.0, 1.0, 1.0'
>>> to_str(np.ones((1,3))) #np.array
'1.0, 1.0, 1.0'
like image 54
dwitvliet Avatar answered Apr 02 '23 05:04

dwitvliet


str is able to convert any type into string. It can be numpy.array / list / float

# using numpy array
new_array = numpy.array([1,2,3])
str(new_array)
>> '[1 2 3]'

# using list
new_list = [1, 2, 3]
str(new_list)
>> '[1, 2, 3]'

# using float
new_float = 1.1
str(new_float)
>> '1.1'
like image 33
Sudip Kafle Avatar answered Apr 02 '23 04:04

Sudip Kafle