Pandas:根据唯一值获取行中对应的列值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40047224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas: Get corresponding column value in row based on unique value
提问by aberger
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 'b' that corresponds to the value of 10 in 'a'.
我想在保存我指定的数据元素的行中的不同列中获取值。例如,'b' 中的值对应于 'a' 中的值 10。
>>> 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”中的所有相应值?
回答by EdChum
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':
您可以使用布尔掩码 withloc
返回满足布尔条件的所有行,这里我们用条件“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