[英]Get column value of row with condition based on another column
I keep writing code like this, when I want a specific column in a row, where I select the row first based on another column.当我想要一行中的特定列时,我一直在编写这样的代码,其中我 select 该行首先基于另一列。
my_col = "Value I am looking for"
df.loc[df["Primary Key"] == "blablablublablablalblalblallaaaabblablalblabla"].iloc[0][
my_col
]
I don't know why, but it seems weird.我不知道为什么,但它看起来很奇怪。 Is there a more beautiful solution to this?有没有更漂亮的解决方案?
It would be helpful with a complete minimally working example, since it is not clear what your data structure looks like.一个完整的最小工作示例会很有帮助,因为不清楚您的数据结构是什么样的。 You could use the example given here :您可以使用此处给出的示例:
import pandas as pd
df = pd.DataFrame([[1, 2], [4, 5], [7, 8]],
index=['cobra', 'viper', 'sidewinder'],
columns=['max_speed', 'shield'])
If you are then trying to eg select the viper
-row based on its max_speed
, and then obtain its shield
-value like so:如果您然后尝试基于其max_speed
的 select viper
-row,然后像这样获取其shield
-value:
my_col = "shield"
df.loc[df["max_speed"] == 4].iloc[0][my_col]
then I guess that is the way to do that - not a lot of fat in that command.那么我想这就是做到这一点的方法 - 该命令中的内容并不多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.