简体   繁体   English

获取具有基于另一列的条件的行的列值

[英]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.

相关问题 当对应的值为NaN时,如何根据另一列中的条件从前一行获取一个值? - How to get a value from a previous row when the corresponding value is NaN based on a condition in another column? 根据Pandas中第二列的条件,用另一行的同一列的值填充特定行的列中的值 - Fill values in a column of a particular row with the value of same column from another row based on a condition on second column in Pandas 使用Python熊猫根据条件将行值复制到另一列 - Copy a row value to another column based on condition using Python pandas 根据另一列的日期戳条件打印行 - Printing row based on datestamp condition of another column 根据条件识别具有行中第一个值的列 - Identifying column with the first value in the row based on a condition 根据条件将列值替换为另一个表中的列值? - Replace column value with column value in another table based on condition? 根据条件转换特定列值,并使用该转换后的值更新另一行 - transform specific column value based on condition and update another row with that transformed value 熊猫根据另一列将条件应用于列值 - pandas apply condition to column value based on another column 如果值落在一个范围内,则根据另一列的条件创建新列 - Create new column based on condition of another column if value falls in a range 根据另一列中的变化条件返回一列中的最大值 - Returning max value in one column based on changing condition in another column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM