简体   繁体   English

如何使用 numpy 将 nan 添加到数组的末尾

[英]How to add nan to the end of an array using numpy

I have a list of multiple arrays and I want them to have the same size, filling the ones with less elements with nan.我有多个 arrays 的列表,我希望它们具有相同的大小,用 nan 填充元素较少的那些。 I have some arrays that have integers and others that have string.我有一些 arrays 有整数和其他有字符串。

For example:例如:

a = ['Nike']
b = [1,5,10,15,20]
c = ['Adidas']
d = [150, 2]

I have tried我努力了

max_len = max(len(a),len(b),len(c),len(d))

empty = np.empty(max_len - len(a))
a = np.asarray(a) + empty

empty = np.empty(max_len - len(b))
b = np.asarray(b) + empty

I do the same with all of the arrays, however an error occurs (TypeError: only integer scalar arrays can be converted to a scalar index)我对所有 arrays 执行相同操作,但是发生错误(TypeError:只有 integer 标量 arrays 可以转换为标量索引)

I am doing this because I want to make a DataFrame with all of the arrays being a different columns.我这样做是因为我想制作一个 DataFrame ,所有 arrays 都是不同的列。

Thank you in advanced谢谢先进

I'd suggest using lists since you also have strings .我建议使用lists ,因为您也有strings Here's one way using zip_longest :这是使用zip_longest的一种方法:

from itertools import zip_longest

a, b, c, d = map(list,(zip(*zip_longest(a,b,c,d, fillvalue=float('nan')))))

print(a)
# ['Nike', nan, nan, nan, nan]

print(b)
# [1, 5, 10, 15, 20]

print(c)
# ['Adidas', nan, nan, nan, nan]

print(d)
# [150, 2, nan, nan, nan]

Another approach could be:另一种方法可能是:

max_len = len(max([a,b,c,d], key=len))
a, b, c, d = [l+[float('nan')]*(max_len-len(l)) for l in [a,b,c,d]]

How about this?这个怎么样?

df1 = pd.DataFrame([a,b,c,d]).T

You should use the numpy.append(array, value, axis) to append to an array.您应该使用numpy.append(array, value, axis)到 append 到一个数组。 In you example that would be ans = np.append(a,empty) .在您的示例中,这将是ans = np.append(a,empty)

You can do that directly just like so:您可以像这样直接执行此操作:

>>> import pandas as pd

>>> a = ['Nike']
>>> b = [1,5,10,15,20]
>>> c = ['Adidas']
>>> d = [150, 2]

>>> pd.DataFrame([a, b, c, d])
        0    1     2     3     4
0    Nike  NaN   NaN   NaN   NaN
1       1  5.0  10.0  15.0  20.0
2  Adidas  NaN   NaN   NaN   NaN
3     150  2.0   NaN   NaN   NaN

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

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