a method of storing elements obtained by a for statement in a first row

Asked 2 years ago, Updated 2 years ago, 282 views

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=",")

python python3

2022-09-30 21:54

2 Answers

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


2022-09-30 21:54

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


2022-09-30 21:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.