python-3.x - 如何在 Pandas 中保存用户输入而不在同一行上覆盖数据
问题描述
每当我尝试接受新用户输入时,它都会覆盖旧用户输入
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)
i=i+1
print(df)
我想知道我是否可以将输入保存在一行中,然后当程序再次运行时,它会将输入保存在下一行,依此类推
解决方案
尝试:
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 label
or list of column labels
。因为它在for
循环中,所以每次迭代都会重置。您需要将其移出循环才能使其生效。
推荐阅读
- swift - 在 SwiftUI 中旋转视图以始终面对鼠标指针
- python-3.x - 在使用 Python 比较 Granger 因果检验中的两个相同时间序列时,获得意外的 p 值 1.0
- json - 使用 axios.get 从静态目录加载 json 文件
- r - 使用正则表达式查找类似的所有模式匹配
- javascript - JavaScript HashTable 类意外令牌错误
- amazon-web-services - 如何在AWS公共的RDS数据库实例中连接,可访问性不起作用
- javascript - 如何在不丢失分辨率的情况下使 Canvas HTML 图片更大?
- haskell - 在两个函数的输入上解析错误 - Haskell
- javascript - 在 JS 或 jQuery 中执行关键帧动画
- unity3d - 如何从预制按钮调用函数?