python - 展开数组并附加行名称

标签 python arrays pandas numpy

我有一个输入文件 foo.txt,其中包含以下几行

A 1 2 3
B 4 5 6
C 7 8 9

我写了以下几行

import numpy as np
import pandas as pd

file="foo.txt"

source_array=pd.read_csv(file, sep=" ", header=None)

name_array=source_array.iloc[:,0].to_numpy()
number_array=source_array.iloc[:,1:4].to_numpy()

r1=np.array([[1,0,0],[0,1,0],[0,0,1]])
r2=np.array([[0.5,-0.30902,-0.80902],[0.30902,-0.80902,0.5],[-0.80902,-0.5,-0.30902]])
r3=np.array([[0.5,0.30902,-0.80902],[-0.30902,-0.80902,-0.5],[-0.80902,0.5,-0.30902]])
mult_array=np.array([r1,r2,r3])

out_array=np.empty((0,3))
for i in range(number_array.shape[0]):
    lad=number_array[i,0:3]
    lad=lad.reshape(1,3)
    print(lad)
    for j in range(mult_array.shape[0]):
        operated_array=np.dot(lad,mult_array[j])
        out_array=np.append(out_array,operated_array,axis=0)
        #print(operated_array)
    np.savetxt('foo2.txt',out_array, fmt='%.2f')

执行 do 乘法后,我得到以下输出

1.00 2.00 3.00
-1.31 -3.43 -0.74
-2.55 0.19 -2.74
4.00 5.00 6.00
-1.31 -8.28 -2.59
-4.40 0.19 -7.59
7.00 8.00 9.00
-1.31 -13.14 -4.44
-6.25 0.19 -12.44

但是 foo2.txt 中的预期输出是

A 1.00 2.00 3.00
A -1.31 -3.43 -0.74
A -2.55 0.19 -2.74
B 4.00 5.00 6.00
B -1.31 -8.28 -2.59
B -4.40 0.19 -7.59
C 7.00 8.00 9.00
C -1.31 -13.14 -4.44
C -6.25 0.19 -12.44

如何在执行点乘法时多次重复行名称?

为了清楚起见,输入 print(df) 输出为

df
   0  1  2  3
0  A  1  2  3
1  B  4  5  6
2  C  7  8  9

最佳答案

我们不需要for循环,同样需要借助explode

df['new']=np.dot(df,mult_array).tolist()
s=df.new.explode()
output=pd.DataFrame(s.tolist(),index=s.index).round(2)
Out[30]: 
      0      1      2
A  1.00   2.00   3.00
A -1.31  -3.43  -0.74
A -2.55   0.19  -2.74
B  4.00   5.00   6.00
B -1.31  -8.28  -2.59
B -4.40   0.19  -7.59
C  7.00   8.00   9.00
C -1.31 -13.14  -4.44
C -6.25   0.19 -12.44

数据输入

df
   0  1  2
A  1  2  3
B  4  5  6
C  7  8  9

关于python - 展开数组并附加行名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63569995/

相关文章:

python - Python 中区分大小写的字符串比较

python - 查找前面没有其他字符串的字符串

python - 如何减少 elif 语句

c# - 使用索引 C# 返回数组的子集

arrays - Swift 3.1 : Array too large to be initialized?(程序卡住)

python - python 格式说明符中的变量

java - 统计 ArrayList 中一定范围内的数字

python - Double Group-by 然后应用一些功能?

python - 如何在 python 中将 pandas.qcut 作为 sqlalchemy 查询的一部分应用?

python - Pandas 条件创建多列