简体   繁体   中英

Iterate over column values in a dataframe - pandas

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

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))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM