[英]Reading multi-dimensional arrays from text file and storing the data in multi-dimensional arrays
[英]Storing output multi 1 dimensional arrays as a data file
import numpy as np
import matplotlib.pyplot as plt
x = open(r'''C:\Users\Documents\ex.txt''')
[INPUT ex.txt file:
-1.642195902 0.751055263
0.496998351 -1.306558434
-0.490237525 -0.188855324
-1.357284374 0.282238191
-0.160982328 -1.115393803
1.167022948 0.564800286
-2.050084963 0.262537079
0.883449292 -0.276800002
1.017703957 -0.044710318
0.194025051 -1.392772391
0.209566571 -0.314937244
1.840331474 -1.544109096
0.493878872 -0.405593557
]
ls = x.readlines()
x1 = np.array([])
x2 = np.array([])
for l in ls:
col = l.split()
x1 = np.append(x1,float(col[0]))
x2 = np.append(x2,float(col[1]))
x3 = np.polyfit(x1,x2,1)
print(x3)
Output is:
[-0.22867408 0.37552763]
[-0.96186389 -0.82851367]
[-0.95783751 -0.77027985]
[-0.90374253 -0.79169204]
[-0.97569702 -0.93091431]
[-0.29008702 -0.26483726]
[-0.27811928 -0.26755408]
.........
[-0.06747052 -0.0218189 ]
我的目標是使用x3的值並從原始值x1和x2中減去,我當時想將輸出另存為.txt文件,但輸出是幾個1維數組。
有誰知道如何保存x3的結果,以便能夠從原始值中減去它? 我不確定如何編碼。 我的目標是趨勢化一組數據。
非常感謝
嘗試這個:
import numpy as np
import matplotlib.pyplot as plt
x = open(r'''C:\Users\Documents\ex.txt''')
ls = x.readlines()
x1 = np.array([])
x2 = np.array([])
x_array = np.array([])
x3_array = np.array([])
for l in ls:
col = l.split()
x_array = np.append(x_array, [float(col[0]), float(col[1])])
x1 = np.append(x1,float(col[0]))
x2 = np.append(x2,float(col[1]))
x3_array = np.append(x3_array, np.polyfit(x1,x2,1))
sub_res = x_array - x3_array
print (sub_res)
首先關於導入數據:
data = np.genfromtxt('c:/Users/kaufnbnj/Desktop/ex.txt', names = ['x1', 'x2'])
array([(-1.6421959 , 0.75105526), ( 0.49699835, -1.30655843),
(-0.49023753, -0.18885532), (-1.35728437, 0.28223819),
(-0.16098233, -1.1153938 ), ( 1.16702295, 0.56480029),
(-2.05008496, 0.26253708), ( 0.88344929, -0.2768 ),
( 1.01770396, -0.04471032), ( 0.19402505, -1.39277239),
( 0.20956657, -0.31493724), ( 1.84033147, -1.5441091 ),
( 0.49387887, -0.40559356)],
dtype=[('x1', '<f8'), ('x2', '<f8')])
訪問第一列:
data['x1']
array([-1.6421959 , 0.49699835, -0.49023753, -1.35728437, -0.16098233,
1.16702295, -2.05008496, 0.88344929, 1.01770396, 0.19402505,
0.20956657, 1.84033147, 0.49387887])
然后是配件部分:
x3 = np.polyfit(data['x1'], data['x2'], 1)
請注意, polyfit
返回擬合函數的系數,而不是輸入數據的采樣數組:
x3
array([-0.33019369, -0.3484815 ])
因此,您可以繪制輸入數據並擬合如下所示的圖:
x_fit = x3[0]*data['x1'] + x3[1]
plt.plot(data['x1'], data['x2'], 'o')
plt.plot(data['x1'], x_fit)
...且下降趨勢后的x2為:
x_detrend = data['x2'] - x_fit
plt.plot(data['x1'], x_detrend, 'o')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.