【问题标题】:How to replace column values with results from for loop?如何用 for 循环的结果替换列值?
【发布时间】:2021-08-26 07:45:18
【问题描述】:

我的数据框看起来像这样:

teams    x_in_mins    y_in_mins   z_in_mins
team_a      50            120         24
team_b      80            66          30
team_c      30            90          70

我想将整数列(代表总分钟数)转换为时间格式(小时和分钟)。

对于这一步,我创建了一个 for 循环:

for column in df[["x_in_mins","y_in_mins","z_in_mins"]]:
    print(pd.to_timedelta(df[column], unit='min'))

这会遍历指定的列,将整数转换为 timedelta。

然后如何将 for 循环结果放入新的数据帧?

最终的数据框应如下所示:

teams    x_in_hrs    y_in_hrs   z_in_hrs
team_a    00:40:00    02:00:00    00:24:00
team_b    01:20:00    01:06:00    00:30:00
team_c    00:30:00    01:30:00    01:10:00

【问题讨论】:

  • team_A x_in_hrs 不应该是 00:50:00 吗?

标签: python pandas dataframe for-loop


【解决方案1】:

你可以使用transform:

def foo(col):
    return pd.to_timedelta(col, unit='min').astype(str).str.rsplit().str[-1]

df[["x_in_mins","y_in_mins","z_in_mins"]].transform(foo)

【讨论】:

    【解决方案2】:

    如果您希望结果格式为 'hh:mm:ss' 而不是 '0 days hh:mm:ss'(如果您确定分钟数不会超过 24 小时)并且还希望将列标签从 *_in_mins 重命名为*_in_hrs,你可以使用:

    .filter()选择列:

    cols = df.filter(like='in_mins').columns
    

    然后,将分钟转换为'hh:mm:ss'

    df[cols].apply(lambda x: pd.to_timedelta(x, unit='min').astype(str).str[-8:])
    

    最后,重命名列标签:

    df.columns = df.columns.str.replace('in_mins', 'in_hrs')
    

    结果:

    print(df)
    
        teams  x_in_hrs  y_in_hrs  z_in_hrs
    0  team_a  00:50:00  02:00:00  00:24:00
    1  team_b  01:20:00  01:06:00  00:30:00
    2  team_c  00:30:00  01:30:00  01:10:00
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      • 2019-04-04
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多