TransWikia.com

How to save txt file and make two column table using python?

Stack Overflow Asked by ashice on November 17, 2021

i am trying to write simple python code for trajectory

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

and output is txt file but empty and table appear like this

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

how can i convert it into two columns

i import numpy and

One Answer

There are extra spaces after first input. I think the best solution is using pandas:

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)

Answered by Nose on November 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP