np.arange在调整大小时创建一个空值矩阵



以下是我正在使用的代码:

import numpy as np
import pandas as pd
from pandas import DataFrame, Series
animals = DataFrame(np.arange(16).resize(4, 4), columns=['W', 'X', 'Y', 'Z'], index=['Dog', 'Cat', 'Bird', 'Mouse'])
print(animals)

我得到的输出是:

W    X    Y    Z
Dog    NaN  NaN  NaN  NaN
Cat    NaN  NaN  NaN  NaN
Bird   NaN  NaN  NaN  NaN
Mouse  NaN  NaN  NaN  NaN

我期望的输出是:

W    X    Y    Z
Dog      0    1    2    3
Cat      4    5    6    7
Bird     8    9   10   11
Mouse    12   13   14   15

然而,如果我只运行:

print(np.arange(16))

我得到的输出是:

[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]

使用整形

import pandas as pd
animals = pd.DataFrame(np.arange(16).reshape(4, 4), columns=['W', 'X', 'Y', 'Z'], index=['Dog', 'Cat', 'Bird', 'Mouse'])
print(animals)

或使用numpy.resize((

np.resize(np.arange(16),(4, 4))

使用resize需要将数组作为参数传递

import pandas as pd
animals = pd.DataFrame(np.resize(np.arange(16),(4, 4)), columns=['W', 'X', 'Y', 'Z'], index=['Dog', 'Cat', 'Bird', 'Mouse'])
print(animals)

ndarray.resize((将执行就地操作。因此,预先计算大小,然后创建一个数据帧

a=np.arange(16)
a.resize(4,4)
import pandas as pd
animals = pd.DataFrame(a, columns=['W', 'X', 'Y', 'Z'], index=['Dog', 'Cat', 'Bird', 'Mouse'])
print(animals)

从调整大小的文档中:"就地更改数组的形状和大小。"因此,您对resize的调用返回None

您需要reshape。如np.arange(16).reshape(4, 4)

添加到上面的答案中,resize:的文档

ndarray.resize(new_shape, refcheck=True)

更改阵列的形状和大小。

因此,与reshape不同,resize不会创建新数组。事实上,np.arange(16).resize(4, 4)产生None,这就是为什么得到Nan值的原因。

使用reshape返回一个新数组:

ndarray.reshape(shape, order='C')

返回一个数组,该数组包含具有新形状的相同数据

最新更新