[英]How can I print the value based on conditions on pandas Dataframe?
I'm new to pandas dataframe and python.我是 pandas dataframe 和 python 的新手。 Currently, I have a pandas dataframe which I'd like to print the values based on conditions set.
目前,我有一个 pandas dataframe ,我想根据设置的条件打印值。
My df looks like this:我的 df 看起来像这样:
ID Name Price
1 Apple 1
2 Orange 0.5
3 Pear 0.7
I'd like to code it such that when I ask the user to input the ID, it will return the price.我想对其进行编码,以便当我要求用户输入 ID 时,它会返回价格。 For example, if the user input 2, it should return 0.5.
例如,如果用户输入 2,它应该返回 0.5。
inputid = input("Please input ID: ")
What should I do next to get return Price from df based on the input?接下来我应该怎么做才能根据输入从 df 获取返回价格?
One of possible solutions:可能的解决方案之一:
Set ID column in df as its index:将df中的ID列设置为其索引:
df.set_index('ID', inplace=True)
Define the following function:定义如下 function:
def getPrice(): inputid = input("Please input ID: ") try: return df.loc[int(inputid), 'Price'] except: return 'No such ID'
Then when you call it, executing getPrice()
:然后当你调用它时,执行
getPrice()
:
The Pandas documentation is very good and will cover everything you need. Pandas 文档非常好,将涵盖您需要的一切。
https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html
Let's call your DataFrame price_df
, depending on whether your ID column is set as the index of the dataframe or not.让我们调用您的 DataFrame
price_df
,具体取决于您的 ID 列是否设置为 dataframe 的索引。
If it is:如果是:
print(price_df.loc[inputid, "Price"])
If it isn't:如果不是:
print(price_df[price_df["ID"] == inputid]["Price"])
The .loc
method is the primary way of accessing data from a DataFrame. .loc
方法是从 DataFrame 访问数据的主要方式。
Here is a working solution.这是一个可行的解决方案。
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
You need to change the user input to float
or int
for pandas to read.您需要将用户输入更改为
float
或int
以便 pandas 读取。
You can try:你可以试试:
userin = input("input ID: ")
print("The price for the ID is- ",df[df.ID==float(userin)].Price.values[0])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.