如何根据Panda Dataframe上的条件打印值



我是熊猫数据框架和python的新手。目前,我有一个pandas数据帧,我想根据设置的条件打印值。

我的df看起来是这样的:

ID     Name    Price
1      Apple     1
2      Orange    0.5
3      Pear      0.7

我想对它进行编码,这样当我要求用户输入ID时,它就会返回价格。例如,如果用户输入2,它应该返回0.5。

inputid = input("Please input ID: ")

接下来我应该怎么做才能根据输入从df获得退货价格?

可能的解决方案之一:

  1. df中的ID列设置为其索引:

    df.set_index('ID', inplace=True)
    
  2. 定义以下功能:

    def getPrice():
    inputid = input("Please input ID: ")
    try:
    return df.loc[int(inputid), 'Price']
    except:
    return 'No such ID'
    

然后当您调用它时,执行getPrice():

  • 将显示一个输入提示
  • 用户输入ID
  • try块内,此函数尝试:
    • inputid转换为int(索引包含int值,但是inputid字符串(,因此错误的一个原因可能是用户只是按下Enter而没有输入任何值
    • 即使用户输入了一个数字,df也可能不包含这样的ID(第二个错误原因(
  • 如果到目前为止一切正常,函数将返回利息的价格
  • 但是,如果出现任何错误,结果就是一条错误消息

Pandas文档非常好,将涵盖您所需要的一切。

https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html

让我们调用您的DataFrameprice_df,这取决于您的ID列是否设置为数据帧的索引。

如果是:

print(price_df.loc[inputid, "Price"])

如果不是:

print(price_df[price_df["ID"] == inputid]["Price"])

.loc方法是从DataFrame访问数据的主要方式。

这是一个有效的解决方案。

df = pd.DataFrame({'ID' : (1, 2,3),
'Name':('Apple', 'Orange', 'Pear'),
'Price': (1, 0.5, 0.7)})
df
ID  Name    Price
0   1   Apple   1.0
1   2   Orange  0.5
2   3   Pear    0.7
userin = input("Please input ID: ")
userin
`1`
df.loc[df['ID'] == float(userin)]
ID  Name    Price
0   1   Apple   1.0

您需要将用户输入更改为floatint,以便panda读取。

您可以尝试:

userin = input("input ID: ")

print("The price for the ID is- ",df[df.ID==float(userin)].Price.values[0])

最新更新