pandas 如何从“groupby”对象的“单元格”获取值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15002085/
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
How to get values from a "cell" of a "groupby" object?
提问by Roman
Assume that I have the following data frame:
假设我有以下数据框:
A B C D
0 foo one 1 10
1 bar one 2 20
2 foo two 3 30
3 bar one 4 40
4 foo two 5 50
5 bar two 6 60
6 foo one 7 70
7 foo two 8 80
Now I can group by the first column: grouped = df.groupby('A'). As a result I get the following DataFrameGroupByobject:
现在我可以按第一列分组:grouped = df.groupby('A')。结果我得到以下DataFrameGroupBy对象:
A B C D
0 foo [one,two,two,one,two] [1,3,5,7,8] [10,30,50,70,80]
1 bar [one,one,two] [2,4,6] [20,40,60]
Now I would like to access the values from a particular cell. How can I do it? For example I want to get the values from the column 'D' and the row where 'A'=='foo'(the first row). In other words I want to get [10,30,50,70,80]. Is it possible?
现在我想从特定单元格访问值。我该怎么做?例如,我想从列 'D' 和行'A'=='foo'(第一行)中获取值。换句话说,我想得到[10,30,50,70,80]. 是否可以?
回答by DSM
Are you thinking of something like this?
你在想这样的事情吗?
>>> df
A B C D
0 foo one 1 10
1 bar one 2 20
2 foo two 3 30
3 bar one 4 40
4 foo two 5 50
5 bar two 6 60
6 foo one 7 70
7 foo two 8 80
>>> df.groupby("A").get_group("foo")["D"]
0 10
2 30
4 50
6 70
7 80
Name: D
>>> df.groupby("A").get_group("foo")["D"].tolist()
[10, 30, 50, 70, 80]

