Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get values from a "cell" of a "groupby" object?

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 DataFrameGroupBy object:

     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?

like image 654
Roman Avatar asked Feb 21 '13 12:02

Roman


People also ask

How do I turn a Groupby object into a list?

You can group DataFrame rows into a list by using pandas. DataFrame. groupby() function on the column of interest, select the column you want as a list from group and then use Series. apply(list) to get the list for every group.

How do I get a specific cell in pandas?

In Pandas, DataFrame. loc[] property is used to get a specific cell value by row & label name(column name).

How do I get the values of a column in a DataFrame?

You can use the loc and iloc functions to access columns in a Pandas DataFrame. Let's see how. If we wanted to access a certain column in our DataFrame, for example the Grades column, we could simply use the loc function and specify the name of the column in order to retrieve it.


2 Answers

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]
like image 130
DSM Avatar answered Oct 13 '22 08:10

DSM


It's possible by this statement:

>>> df.groupby("A").get_group("foo")["D"]
0    10
2    30
4    50
6    70
7    80
Name: D
like image 37
Ehsan Barkhordar Avatar answered Oct 13 '22 08:10

Ehsan Barkhordar