我是熊猫数据框和python的新手。 目前,我有一个熊猫数据框,我想根据设置的条件打印值。
我的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获得退回价格?
答案 0 :(得分:1)
可能的解决方案之一:
将 df 中的 ID 列设置为其索引:
df.set_index('ID', inplace=True)
定义以下功能:
def getPrice():
inputid = input("Please input ID: ")
try:
return df.loc[int(inputid), 'Price']
except:
return 'No such ID'
然后在您调用它时执行getPrice()
:
答案 1 :(得分:0)
Pandas文档非常好,可以满足您的所有需求。
https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html
根据您的ID列是否设置为数据框的索引,让我们调用数据框price_df
。
如果是:
print(price_df.loc[inputid, "Price"])
如果不是:
print(price_df[price_df["ID"] == inputid]["Price"])
.loc
方法是从DataFrame访问数据的主要方法。
答案 2 :(得分:0)
这是一个可行的解决方案。
enum Enumeration {
case opt1
case op2
}
struct CustomItem {
var firstItem: Enumeration
let data: Any
}
extension CustomItem: Equatable {
static func ==(lhs: CustomItem, rhs: CustomItem) -> Bool {
return lhs.firstItem == rhs.firstItem
}
}
class ViewController: UIViewController {
var customArray = [CustomItem]()
func searchAndDestory() {
let index = customArray.firstIndex(of: CustomItem.init(firstItem: .op2, data: 0)) ?? 0
customArray.remove(at: index)
}
}
您需要将用户输入更改为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
才能读取大熊猫。
答案 3 :(得分:0)
您可以尝试:
userin = input("input ID: ")
print("The price for the ID is- ",df[df.ID==float(userin)].Price.values[0])