【问题标题】:How to save txt file and make two column table using python?如何使用python保存txt文件并制作两列表?
【发布时间】:2020-07-22 01:05:27
【问题描述】:

我正在尝试为轨迹编写简单的 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 和

【问题讨论】:

    标签: python python-3.x plot multiple-columns requirements.txt


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 感谢您的回复,我希望最后有表格作为输出。此代码未在输出中显示任何表格
    猜你喜欢
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多