python - 无论用户输入是否有大写字母,如何从 df 获取值
问题描述
我有一个df
如下:
BDEW Article
0 999 Cola
1 998 Fanta
2 997 Sprite
3 996 Dew
4 995 Water
我们可以看到列中每篇文章的第一个字母都Article
以大写字母开头。我要求用户选择一篇文章。如果用户在开始时输入带有大写字母的名称,我的代码可以正常工作。但是,如果用户提供输入cola
而不是Cola
,我会收到错误消息:
是否要添加细分 (Y/N)?:y
您想添加哪篇文章?:cola Traceback(最近一次通话最后一次):
文件“”,第 5 行,在 bdew_value = df.loc[df['Article'] == article, 'BDEW'].iloc[0]
文件“C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\pandas\core\indexing.py”,第 1410 行,在getitem 返回 self._getitem_axis(maybe_callable,axis=axis)
_getitem_axis self._validate_integer(key, axis) 中的文件“C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\pandas\core\indexing.py”,第 2132 行
_validate_integer 中的文件“C:\Users\kashy\Anaconda3\envs\py36\lib\site-packages\pandas\core\indexing.py”,第 2063 行引发 IndexError(“单个位置索引器越界”)
IndexError:单个位置索引器超出范围
我认为错误是因为我.iloc
在我的代码中使用。
有没有办法可以克服这个问题,即使用户在开头插入一个带有小写字母的名称,代码也应该可以工作。
我的代码:
i = 0
while True:
add_seg = input('Do you want to add a segment (Y/N)?: ')
if (add_seg == 'Y')|(add_seg == 'y'):
article = (input('Which article would you like to add?: ')).lower()
bdew_value = df.loc[df['Article'] == article, 'BDEW'].iloc[0]
i = i + 1
INVOIC.add_segment(Segment('LIN', str(i), '', [str(bdew_value), 'Z01']))
elif (add_seg == 'N')|(add_seg == 'n'):
break
解决方案
将用户给出的输入转换为大写,然后进行比较。就像是:
article = (input('Which article would you like to add?: ')).upper()
您说过,要使程序正常工作,第一个字母必须是大写字母。所以我想其余的都无所谓。
或者,如果您愿意,您只能将第一个字母转换为大写字母:
article = (input('Which article would you like to add?: ')).capitalize()
推荐阅读
- html - 是否可以在 DocBook 5 中创建和使用模板结构?
- reactjs - 了解从目录导入模块的 React.js 导入语句
- node.js - 使用 npm 模块 activedirectory 时出错:“TypeError:activedirectory 不是构造函数”
- python - 如何防止 keras 自定义损失函数中的负面预测
- android - 找不到参数的方法 implementation() [android.arch.lifecycle:extensions:1.1.1]
- laravel - “未定义索引:密码” laravel 5.6
- fn - 如何将驱动程序从 Docker 更改为 Mocker
- angular - 角度 - 打字稿错误类型AnimatesDirective
- c# - 异步操作的锁定替代方案
- javascript - 如何将此表单放入 AJAX 请求中