How to combine np string array with float array python

↘锁芯ラ 提交于 2019-12-11 20:36:20

问题


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.


回答1:


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:


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)


来源:https://stackoverflow.com/questions/31468188/how-to-combine-np-string-array-with-float-array-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!