I tried to display the value of Y when I specified X in the following program. So I tried to save this value of Y in a csv file in a column, but a=np.array(f_CS(xnew)) only reflected the element when i was 40.
import pandas as pd
from scipy.interpolate import interp1d
import numpy as np
import matplotlib.pyplot asplt
date = "1214"
x = np.array ([0, 6, 11, 20, 30, 40])
y = np.array ([92, 105, 114, 125, 148, 141])
f_line=interp1d(x,y)
f_CS=interp1d(x,y,kind='cubic')
time_list = np.array ([0, 3, 11, 20, 30, 40])
# for plot
xnew=np.linspace(0,40,num=50)
plt.plot(x,y,'o')
plt.plot(xnew, f_CS(xnew), '-')
for in time_list:
print('X=',i,' value of Y =',str(f_CS(i)))
a=np.array(f_CS(xnew))
np.savetxt(f"{date}-target", a, delimiter=",")
The numpy.savetxt parameter fname
specifies filename or file handle
The file name specification seems to be intended for one-time use (not limited to numpy.savetxt
.
No matter how many times I call you, I will create and write a new file, so as a result, I only have the last start left.
You must use the file handle.
with open(f"{date}-target", 'w') as fp:
for in time_list:
print( value of Y when f'X = {i:2} = {f_CS(i)}')
a=np.array(f_CS(xnew))
np.savetxt(fp, [a], delimiter=", ")
A value based on time_list
rather than 50 equal parts, then you can do the following
for in time_list:
print( value of Y when f'X = {i:2} = {f_CS(i)}')
with open(f"{date}-target", 'w') as fp:
np.savetxt(fp, f_CS(time_list), fmt='%s')
Create a text file using the built-in function open().
import pandas as pd
from scipy.interpolate import interp1d
import numpy as np
import matplotlib.pyplot asplt
date = "1214"
x = np.array ([0, 6, 11, 20, 30, 40])
y = np.array ([92, 105, 114, 125, 148, 141])
f_line=interp1d(x,y)
f_CS=interp1d(x,y,kind='cubic')
time_list = np.array ([0, 3, 11, 20, 30, 40])
# for plot
xnew=np.linspace(0,40,num=50)
plt.plot(x,y,'o')
plt.plot(xnew, f_CS(xnew), '-')
with open(f"{date}-target", 'w') as f:
for in time_list:
print('X=',i,' value of Y =',str(f_CS(i)))
f.write(str(f_CS(i))+'\n')
© 2025 OneMinuteCode. All rights reserved.