Home > Back-end >  Iterate over column values in a dataframe - pandas
Iterate over column values in a dataframe - pandas

Time:01-15

I have a table like this

emp_id emp_role mgr_id mgr_role
111 AP 112 SP
112 SP 116 DP
114 LP 115 DP

For each employee, I need to print the emp_role, his mgr_id and mgr_role

I have tried this

for id in df['emp_id']:
    print(id   'with role'   df['emp_role']   'is reporting to'   df['mgr_id']   'with role'   df['mgr_role']

This prints the output multiple times but i need to print it exactly once. Please help to resolve this. Thanks in advance.

Expected output:

111 with role AP is reporting to 112 with role SP
112 with role SP is reporting to 116 with role DP
114 with role LP is reporting to 115 with role DP

CodePudding user response:

You can use the .iterrows() function to iterate through each row of the DataFrame and access the specific values for each column. Here is an example:

for index, row in df.iterrows():
    print(f"{row['emp_id']} with role {row['emp_role']} is reporting to {row['mgr_id']} with role {row['mgr_role']}")

This will iterate through each row of the DataFrame, and for each row, it will print the values of the "emp_id", "emp_role", "mgr_id", and "mgr_role" columns. You can also use f-strings instead of using ' ' to concatenate strings.

CodePudding user response:

I think that you are really close to your approach. Depending on how you defined your table in Python, you can use print with format.

table = [    [111, "AP", 112, "SP"],
    [112, "SP", 116, "DP"],
    [114, "LP", 115, "DP"]
]

for row in table:
  emp_id, emp_role, mgr_id, mgr_role = row
  print("{} with role {} is reporting to {} with role {}".format(emp_id, emp_role, mgr_id, mgr_role))
  • Related