I have a group by object.I want to retrieve rows of a particular column of the group by object in for loop & do some processing. For example,I'm giving here a sample code for group by object
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B' : ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C' : np.random.randn(8),
'D' : np.random.randn(8)})
grouped = df.groupby(['A', 'B'])
After group by, I got following object
In a for loop I would like to do some check if it's one,two or three & then do some processing.Can you please suggest me the steps?
you can loop in the group_by object like this :
for index, row in grouped:
print (index) #index is a tuple
print(row) #row is a new dataframe
To check what you are looking for you can do this(ie: check if a value is in a certain column of a dataframe do this):
for index, row in grouped:
if -0.83026 in row.get("C").values: # "C" or any column name you want
print("hello")
for your data the output will be something like this :
('bar', 'one')
A B C D
1 bar one -0.83026 0.983017
('bar', 'three')
A B C D
3 bar three -0.381041 1.538971
('bar', 'two')
A B C D
5 bar two -0.963402 0.201348
('foo', 'one')
A B C D
0 foo one 0.691410 0.328420
6 foo one -1.521541 -0.188345
('foo', 'three')
A B C D
7 foo three -0.817304 -0.359331
('foo', 'two')
A B C D
2 foo two -0.528639 -0.999301
4 foo two -1.018919 0.661665
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.