[英]How can I “merge” rows in a Pandas DataFrame based on these conditions
[英]How can I print the value based on conditions on pandas Dataframe?
我是 pandas dataframe 和 python 的新手。 目前,我有一个 pandas dataframe ,我想根据设置的条件打印值。
我的 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 获取返回价格?
可能的解决方案之一:
将df中的ID列设置为其索引:
df.set_index('ID', inplace=True)
定义如下 function:
def getPrice(): inputid = input("Please input ID: ") try: return df.loc[int(inputid), 'Price'] except: return 'No such ID'
然后当你调用它时,执行getPrice()
:
Pandas 文档非常好,将涵盖您需要的一切。
https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html
让我们调用您的 DataFrame price_df
,具体取决于您的 ID 列是否设置为 dataframe 的索引。
如果是:
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
您需要将用户输入更改为float
或int
以便 pandas 读取。
你可以试试:
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.