首页 > 解决方案 > 根据 Pandas Dataframe 中的其他单元格查找单元格值

问题描述

          0            1    2
0  this           is  1.0
1    my         book  1.0
2  book         this  1.0
3    is           my  0.5
4    is  interesting  0.5 

我的数据框看起来像这样,但它是动态的。所以它也可以看起来像

      0     1            2    3
0  this    is  interesting  0.5
1    is    my         book  1.0
2  this    is           my  0.5
3    my  book         this  1.0
4  book  this           is  1.0

现在我想从最后一列获取浮点值,以将前三列值的值作为元组给出。像

("this","is") 
("this","is","interesting")

它应该分别给我一个 1.0 和 0.5 的值。请帮我解决这个问题。

目前我正在使用这个

row = df[(df["0"] == "is") & (df["1"] == "my")]

但它不是动态的。

标签: pythonpandasnumpydataframe

解决方案


我不确定这是否是您想要的,看看您是否可以根据您的需要对其进行修改:

 f = ("this","is","interesting")

#condition checks if words can be found in the dataframe
#looks for rows that has all the words
#and converts to an array of True or False
cond = df.iloc[:,:-1].isin(f).all(axis=1).to_numpy()

#filter the dataframe, to get the values from the last column 
#where condition is True
#iloc works with an array or list of Booleans,
#it cannot reference a series label,
#hence then need to convert the cond to a list or array
df.iloc[cond,-1]

0    0.5
Name: 3, dtype: float64

当然,您可以将结果分配给一列...但我不确定这是否是您之后的结果


推荐阅读