gpt4 book ai didi

python - python中如何转置单列数据的问题

转载 作者:行者123 更新时间:2023-11-28 21:50:00 25 4
gpt4 key购买 nike

我创建了一个名为“column.txt”的文本文件,其中包含以下数据:

1
2
3
4
9
8

然后我编写了下面的代码,将我的数据转置为单行文本文件。

import numpy as np
x=np.loadtxt('column.txt')
z=x.T
y=x.transpose()
np.savetxt('row.txt',y, fmt='%i')

我尝试了两种不同的方法——使用矩阵乘法(我代码中的注释行)和使用转置命令。问题是输出与输入完全相同!

之后,我在输入文件中添加了另一列,运行代码,令人惊讶的是这次输出完全正常(输出包含两行!)

所以我的问题是:

有没有办法将单列文件转置为单行文件?如果是,你能描述一下怎么做吗?

最佳答案

您可以使用 numpy.reshape转置数据并更改数组的形状,如下所示:

>>> import numpy as np
>>> arr=np.loadtxt('column.txt')
>>> arr
array([ 1., 2., 3., 4., 9., 8.])
>>> arr.shape
(6,)
>>> arr=arr.reshape(6,1)
>>> arr
array([[ 1.],
[ 2.],
[ 3.],
[ 4.],
[ 9.],
[ 8.]])

或者您可以将数组维度的数量作为 numpy.loadtxt 的输入功能

>>> np.loadtxt('column.txt', ndmin=2)
array([[ 1.],
[ 2.],
[ 3.],
[ 4.],
[ 9.],
[ 8.]])

但是如果你想将单列转换为单行并将其写入文件,你只需要按照以下操作

>>> parr=arr.reshape(1,len(arr))
np.savetxt('column.txt',parr, fmt='%i')

关于python - python中如何转置单列数据的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32521982/

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