简体   繁体   English

将 numpy 数组从空格分隔转换为 python 中的逗号分隔

[英]Convert numpy array from space separated to comma separated in python

This is data in.csv format file generally we expect array/ list with [1,2,3,4] comma separated values which it seems that nothing happened in this case这是.csv 格式文件中的数据,通常我们期望数组/列表具有 [1,2,3,4] 逗号分隔值,在这种情况下似乎没有发生任何事情

data = pd.read_csv('file.csv')
data_array = data.values

print(data_array)

print(type(data_array[0]))

and here is the output data这是 output 数据

[16025788 179 '179batch1640694482' 18055630 8317948789 '2021-12-28'
 8315780000.0 '6214' 'CA' Nan Nan 'Wireless' '2021-12-28 12:32:46'
 '2021-12-28 12:32:46']

<class 'numpy.ndarray'>

So, i am looking for way to find array with comma separated values所以,我正在寻找用逗号分隔值查找数组的方法

Okay so simply make the changes:好的,只需进行更改:

converted_str = numpy.array_str(data_array)
converted_str.replace(' ',',')
print(converted_str)

Now, if you want to get the output in <class 'numpy.ndarray'> simply convert it back to a numpy array.现在,如果您想在 <class 'numpy.ndarray'> 中获取 output,只需将其转换回 numpy 数组即可。 I hope this helps!我希望这有帮助!

Without the csv or dataframe (or at least a sample) there's some ambiguity as to what your data array is like.如果没有csv或 dataframe(或至少一个样本),那么您的data数组是什么样的会有些模糊。 But let me illustrate things with sample.但是让我用样本来说明事情。

In [166]: df = pd.DataFrame([['one',2],['two',3]])

the dataframe display: dataframe 显示:

In [167]: df
Out[167]: 
     0  1
0  one  2
1  two  3

The array derived from the frame:从框架派生的数组:

In [168]: data = df.values
In [169]: data
Out[169]: 
array([['one', 2],
       ['two', 3]], dtype=object)

In my Ipython session, the display is actually the repr representation of the array.在我的 Ipython session 中,显示的实际上是数组的repr表示。 Note the commas, word 'array', and dtype.请注意逗号、单词“array”和 dtype。

In [170]: print(repr(data))
array([['one', 2],
       ['two', 3]], dtype=object)

A print of the array omits those words and commas.数组的print省略了这些单词和逗号。 That's the str format.那是str格式。 Omitting the commas is normal for numpy arrays, and helps distinguish them from lists.省略逗号对于numpy arrays 是正常的,有助于将它们与列表区分开来。 But let me stress that this is just the display style.但让我强调一下,这只是展示风格。

In [171]: print(data)
[['one' 2]
 ['two' 3]]
In [172]: print(data[0])
['one' 2]

We can convert the array to a list:我们可以将数组转换为列表:

In [173]: alist = data.tolist()
In [174]: alist
Out[174]: [['one', 2], ['two', 3]]

Commas are a standard part of list display.逗号是列表显示的标准部分。

But let me stress, commas or not, is part of the display.但让我强调,逗号与否,是显示的一部分。 Don't confuse that with the underlying distinction between a pandas dataframe, a numpy array, and a Python list.不要将其与pandas dataframe、 numpy数组和 ZA72115F35432ZB5639 列表之间的基本区别混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM