0

I need to find the corrispective of an element in another column of a Pandas DataFrame. The DataFrame is like this:

EVENT        CODE          DAY
event01      102934        00/00/0000
event02      021384        00/00/0000
event03      045823        00/00/0000

My script is like this:

for a in df["EVENT"]:
    print(a + " " + code)

//event01 102934
//event02 021384
//event03 045823

For example I would like to find out what is the code associated to the event03 (so 045823). How can I do? Thank you!

James Wood
  • 11
  • 2

2 Answers2

1

I think the simpliest is set_index by column EVENT and then select by DataFrame.loc:

df = df.set_index('EVENT')
print (df)
           CODE         DAY
EVENT                      
event01  102934  00/00/0000
event02  021384  00/00/0000
event03  045823  00/00/0000

For unique values of CODE are unique it return scalar:

print (df.loc['event01', 'CODE'])
102934

print (df.loc['event02', 'CODE'])
021384

print (df.loc['event02', 'DAY'])
00/00/0000

But if multiple values it return Series:

df = df.set_index('EVENT')
print (df)
           CODE         DAY
EVENT                      
event01  103453  00/00/0000
event01  102934  00/00/0000
event02  021384  00/00/0000
event03  045823  00/00/0000

print (df.loc['event01', 'CODE'])
EVENT
event01    103453
event01    102934
Name: CODE, dtype: object

For looping you can use iterrows:

for i, x in df.iterrows():
    print (x['EVENT'] + ' ' + x['CODE'])

event01 102934
event02 021384
event03 045823
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

You can simply filter out all other events and then returning the requested attribute by simply df[df["Event"]== "event01"]["CODE"].

However, if you would like to iterate through all events I would direct you to this answer.

Skeftical
  • 151
  • 6