gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:07:41 27 4
gpt4 key购买 nike

以下是我使用的代码:

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]

最佳答案

使用reshape

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

使用调整大小你需要将数组作为参数传递

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)

关于python - np.arange 在调整大小时创建一个空值矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53070618/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com