1

I would like to combine an array full of floats with an array full of strings. Is there a way to do this?

(I am also having trouble rounding my floats, insert is changing them to scientific notation; I am unable to reproduce this with a small example)

A=np.array([[1/3,257/35],[3,4],[5,6]],dtype=float)
B=np.array([7,8,9],dtype=float)
C=np.insert(A,A.shape[1],B,axis=1)
print(np.arround(B,decimals=2))
D=np.array(['name1','name2','name3'])

How do I append D onto the end of C in the same way that I appended B onto A (insert D as the last column of C)?

I suspect that there is a type issue between having strings and floats in the same array. It would also answer my questions if there were a way to change a float (or maybe a scientific number, my numbers are displayed as '5.02512563e-02') to a string with about 4 digits (.0502).

I believe concatenate will not work, because the array dimensions are (3,3) and (,3). D is a 1-D array, D.T is no different than D. Also, when I plug this in I get "ValueError: all the input arrays must have same number of dimensions."

I don't care about accuracy loss due to appending, as this is the last step before I print.

3 Answers 3

2

Use dtype=object in your numpy array; like bellow:

np.array([1, 'a'], dtype=object)
Sign up to request clarification or add additional context in comments.

Comments

0

Try making D a numpy array first, then transposing and concatenating with C:

D=np.array([['name1','name2','name3']])
np.concatenate((C, D.T), axis=1)

See the documentation for concatenate for explanation and examples: http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html

2 Comments

As D is a 1-D array, D.T is no different than D.
I'm confused. How can D be a one D array and be added onto C? Can you show what the expected final output is?
0

numpy arrays support only one type of data in the array. Changing the float to str is not a good idea as it will only result in values very close to the original value.

Try using pandas, it support multiple data types in single column.

import numpy as np
import pandas as pd
np_ar1 = np.array([1.3, 1.4, 1.5])
np_ar2 = np.array(['name1', 'name2', 'name3'])
df1 = pd.DataFrame({'ar1':np_ar1})
df2 = pd.DataFrame({'ar2':np_ar2})
pd.concat([df1.ar1, df2.ar2], axis=0)

Comments

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.