首页 > 解决方案 > 无论用户输入是否有大写字母,如何从 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

标签: pythonpython-3.xpandas

解决方案


将用户给出的输入转换为大写,然后进行比较。就像是:

article = (input('Which article would you like to add?: ')).upper()

您说过,要使程序正常工作,第一个字母必须是大写字母。所以我想其余的都无所谓。

或者,如果您愿意,您只能将第一个字母转换为大写字母:

article = (input('Which article would you like to add?: ')).capitalize()


推荐阅读