如何将用户输入保存在熊猫中而不会在同一行上覆盖数据

时间:2018-06-29 23:15:50

标签: python-3.x pandas

每当我尝试接受新的用户输入时,它都会覆盖旧的用户输入

WorkManager

我想知道是否可以将输入保存为一行,然后在程序再次运行时将其保存到下一行,依此类推

1 个答案:

答案 0 :(得分:0)

尝试:

import pandas as pd
pd.set_option('display.max_columns', 50)
Comp_Name=input("Company Name/Symbol")
NI_before_Extraordinary_items=int(input("Net income before extraordinary items")) 
TA_beg_yr=int(input('Total assets at the beginning of the year'))
Cash_from_op=int(input("Cash flow from operations"))
Prev_NI_before_Extraordinary_items=int(input("Net income before extraordinary items of the last year"))
TA_t2=int(input('Beginning total assets of the previous year'))

for i in range(0,30):
    Company_stats={'index':[i], 'Company Name':[Comp_Name], 'Net Income': 
    [NI_before_Extraordinary_items],'Total Assets At Beg.of the year': 
    [TA_beg_yr],'Cash flow from operations':Cash_from_op}
    df=pd.DataFrame(Company_stats)
    #df.set_index('index',inplace=True)  <-- this is your problem...
    i=i+1
    #print(df)

输入:

aaa, 111, 222, 333, 444, 555

输出(在.to_dict()中,以便于阅读)

In [356]: df.to_dict()
Out[356]: 
{'Cash flow from operations': {0: 333},
 'Company Name': {0: 'aaa'},
 'Net Income': {0: 111},
 'Total Assets At Beg.of the year': {0: 222},
 'index': {0: 29}}  

.set_index()方法传递column labellist of column labels。因为它在for循环中,所以每次迭代都会重置它。您需要将其移到循环之外才能生效。