[英]Pandas: Get corresponding column value in row based on unique value
I've figured out how to get the information I want, but I would be surprised if there is not a better, more readable way to do so.我已经想出如何获取我想要的信息,但如果没有更好、更易读的方法,我会感到惊讶。
I want to get the value in a different column in the row that holds the data element I specify.我想获取包含我指定的数据元素的行中不同列中的值。 For example, what is the value in column b
that corresponds to the value of 11
in column a
.例如,与列b
中的值11
相对应的 b 列中a
值是多少。
>>> df
a b c
0 10 20 30
1 11 21 31
2 12 22 32
>>> df['b'][df[df['a'] == 11].index.tolist()].tolist()
[21]
This is how I currently solved it, but in practice my dataframes are not named so concisely and I have long strings as column names so the line gets hard to read.这就是我目前解决它的方法,但实际上我的数据框并没有这么简洁地命名,而且我有很长的字符串作为列名,所以这行很难阅读。
EDIT: If the value in 'a' is not unique is there also a way to get all corresponding values in 'b'?编辑:如果'a'中的值不是唯一的,是否还有一种方法可以获取'b'中的所有对应值?
You can use a boolean mask with loc
to return all rows where the boolean condition is met, here we mask the df with the condition where 'a' == 11, and where this is met return all values for 'b':您可以使用带有loc
的布尔掩码来返回满足布尔条件的所有行,这里我们用“a”==11 的条件来掩码 df,并且在满足条件的地方返回“b”的所有值:
In [120]:
df = pd.DataFrame({'a':[10,11,11],'b':np.arange(3), 'c':np.random.randn(3)})
df
Out[120]:
a b c
0 10 0 -1.572926
1 11 1 -0.639703
2 11 2 -1.282575
In [121]:
df.loc[df['a'] == 11,'b']
Out[121]:
1 1
2 2
Name: b, dtype: int32
You can use loc to return all the rows where the condition is met.您可以使用 loc 返回满足条件的所有行。 This code will give you the exact value that corresponds to that row where a condition is met.此代码将为您提供与满足条件的行对应的确切值。
result=df.loc[df['a'] == 11,'b'].values[0]
print(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.