python - 根据 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")]
但它不是动态的。
解决方案
我不确定这是否是您想要的,看看您是否可以根据您的需要对其进行修改:
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
当然,您可以将结果分配给一列...但我不确定这是否是您之后的结果
推荐阅读
- inno-setup - 如何抑制wizard.close的提示
- google-sheets-formula - 使用谷歌表格公式加入表格的列
- reactjs - 如何从 React 中的材料表中检索 selectedRows
- java - Google OR-Tools:在 IDE 中使用
- windows-10 - 对于 Windows 10 ANDROID_HOME 和 ANDROID_SDK_ROOT 环境变量均未导出
- flutter - 在使用 RTL 语言的同时保持 Flutter 布局 LTR
- javascript - 谷歌一键登录可以获取授权码吗?
- c++ - 将 C++ 类成员函数作为参数传递给 C 函数
- java - 异步进程在 javax.ws.rs.*(REST 客户端)中不起作用
- javascript - REACTJS : imageloaded 未定义