【问题标题】:Iterate over column values in a dataframe - pandas迭代数据框中的列值 - pandas
【发布时间】:2023-01-14 23:45:18
【问题描述】:

我有一张这样的桌子

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

对于每个员工,我需要打印 emp_role、他的 mgr_id 和 mgr_role

我试过这个

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

这会多次打印输出,但我只需要打印一次。请帮助解决这个问题。提前致谢。

预期输出:

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

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用 .iterrows() 函数遍历 DataFrame 的每一行并访问每一列的特定值。这是一个例子:

    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']}")
    

    这将遍历 DataFrame 的每一行,对于每一行,它将打印“emp_id”、“emp_role”、“mgr_id”和“mgr_role”列的值。您还可以使用 f-strings 而不是使用 '+' 来连接字符串。

    【讨论】:

      【解决方案2】:

      我认为你真的很接近你的方法。根据您在 Python 中定义表格的方式,您可以使用带格式的打印。

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

      【讨论】:

      猜你喜欢
      • 2019-01-14
      • 1970-01-01
      • 2020-12-22
      • 2014-04-01
      • 2017-01-04
      • 1970-01-01
      • 2021-09-17
      • 2017-11-05
      • 2020-09-28
      相关资源
      最近更新 更多