如何使用python保存txt文件并制作两列表



我正在尝试为轨迹编写简单的python代码

from numpy import *
from pandas import *
from matplotlib.pyplot import *
from tabulate import tabulate    
y1=int(input("Enter initial height:"))
v1=int(input("Enter initial velocity:"))
g=9.8
t=np.linspace(0,0.2,5)
yf=y1+v1*t-0.5*(g*t**2)
print("distance", yf,"Time",t)
file = open('table.txt', 'w')
file.writelines = [yf, t]
file.close()
print(tabulate([yf, t], headers=['distance', 'Time']))

输出是txt文件,但为空,表格显示为这样的

**
distance    Time
--  -------  -----  ----------  ------
2  2.03775  2.051     2.03975   2.004
0  0.05     0.1       0.15      0.2
**

我怎么能把它转换成两列

我导入numpy和

第一次输入后有多余的空格。我认为最好的解决方案是使用熊猫:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
y1 = int(input("Enter initial height:"))
v1 = int(input("Enter initial velocity:"))
g = 9.8
t = np.linspace(0,0.2,5)
yf = y1+v1*t-0.5*(g*t**2)
## make the table
df_trajectory = pd.DataFrame({'time':t,'distance':yf})  
## plot trajectory
plt.plot(df_trajectory['time'],df_trajectory['distance'],'*')
plt.ylabel('Time')
plt.xlabel('Distance')
plt.show()
## export csv (comma delimated text file with header)
df_trajectory.to_csv('output.csv',index=None)

最新更新