简体   繁体   English

根据一列的条件和熊猫中另一列的值创建新列

[英]Create new column based on condition from one column and the value from another column in pandas

I have a DF with time given as hours, minutes or milliseconds.我有一个 DF,时间以小时、分钟或毫秒表示。 The time column has the type float and the time_unit column indicate if it is given as hour, minute or ms. time 列的类型为 float,time_unit 列指示它是按小时、分钟还是毫秒给出。

I want to create aa new column that calculates the amount of seconds.我想创建一个新列来计算秒数。 Thus, I need a function that first checks what time_unit it is, then takes the value from time and performs some transformation to seconds.因此,我需要一个函数,它首先检查它是什么 time_unit,然后从时间中获取值并将其转换为秒。

For example:例如:

if df["time_unit"]="h":
   return df["time"]*60*60 # given hours as int
elseif: ...

My df looks like this:我的 df 看起来像这样:

在此处输入图像描述

I want to create the green column (seconds).我想创建绿色列(秒)。 So, how do I do this in pandas?那么,我该如何在熊猫中做到这一点?

You can create the mapping dict您可以创建映射dict

d = {'h' : 60*60, 'min' : 60, 'ms' : 1/1000}

df['seconds'] = df['time_unit'].map(d) * df['time']
seconds = []
for i,r in df.iterrows():
  if r['time_unit'] == 'h':
    seconds.append(r['time']*3600)
  elif r['time_unit'] == 'min':
    seconds.append(r['time']*60)
  elif r['time_unit'] == 'ms':
    seconds.append(r['time']/1000)
df['seconds'] = seconds

I guess this will work.我想这会奏效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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