如何将NP字符串数组与浮点数组Python结合 [英] How to combine np string array with float array python

查看:116
本文介绍了如何将NP字符串数组与浮点数组Python结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个充满浮点数的数组与一个充满字符串的数组结合起来.有办法吗?

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'])

如何像将B附加到A一样(将D作为C的最后一列插入),如何将D附加到C的末尾?

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)?

我怀疑在同一数组中具有字符串和浮点数之间存在类型问题.它还可以回答我的问题,是否可以将浮点数(或科学数字,我的数字显示为"5.02512563e-02")更改为约4位数字(.0502)的字符串.

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).

我相信串联是行不通的,因为数组的维数是(3,3)和(,3). D是一维数组,D.T与D相同.此外,当我将其插入时,我会收到"ValueError:所有输入数组必须具有相同数量的维数."

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.

推荐答案

numpy数组仅支持数组中的一种数据.将float更改为str不是一个好主意,因为它只会导致值非常接近原始值.

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)

这篇关于如何将NP字符串数组与浮点数组Python结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆