Python开发密码管理器时将字典添加到DataFrame出现空DataFrame问题
无法将字典添加到Pandas DataFrame的修复方案
核心问题
DataFrame.append()为非原地操作,执行后会返回新增行后的新DataFrame对象,原对象不会被修改,你未接收该返回值,所以始终打印空DataFrame- Pandas 1.4及以上版本已弃用
append方法,2.0+版本已完全移除该API,继续使用会触发警告或报错
修复代码
直接接收操作返回值即可解决基础问题,推荐使用全版本兼容的pd.concat写法:
import pandas as pd start = int(input('Welcome to the password manager! Type in pass:')) password = 12345 while True: if start == password: table = pd.DataFrame(columns=['Service', 'Login', 'Password']) service = input('Service name:') login = input('Login:') passw = input('Password:') row = pd.DataFrame([{'Service': service, 'Login': login, 'Password': passw}]) table = pd.concat([table, row], ignore_index=True) print(table.head(3)) break else: print('Access denied') break
如果你仍在使用1.4以下版本的Pandas,也可以直接修改append行的写法:
将table.append(row, ignore_index=True)替换为table = table.append(row, ignore_index=True)
功能优化建议
如果需要支持添加多条密码记录,需将DataFrame初始化逻辑移到循环外,避免每次新增时清空历史数据:
import pandas as pd start = int(input('Welcome to the password manager! Type in pass:')) password = 12345 if start == password: table = pd.DataFrame(columns=['Service', 'Login', 'Password']) # 循环录入多条记录 while True: service = input('请输入服务名称(输入q退出录入):') if service.lower() == 'q': break login = input('请输入登录账号:') passw = input('请输入密码:') row = pd.DataFrame([{'Service': service, 'Login': login, 'Password': passw}]) table = pd.concat([table, row], ignore_index=True) print('已保存的所有密码记录:') print(table) else: print('Access denied')
内容的提问来源于stack exchange,提问作者Nino
相关产品推荐
相关产品推荐

