Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将列格式从秒更改为分钟_Python_Pandas - Fatal编程技术网

Python 将列格式从秒更改为分钟

Python 将列格式从秒更改为分钟,python,pandas,Python,Pandas,我有一个DF,有几列数据,以秒为单位,例如:600,我想用以下格式将其转换为分钟00:10:00 我已经找到了下面的代码并运行了一些测试,它确实如预期的那样工作,但是,我有几个列,我想更改格式,我正在寻找最有效的方法来运行代码,而不必为每个列创建函数 提前谢谢 def format_duration(row): seconds = row.Default_Misc ## changed this minutes, seconds = divmod(seconds, 60

我有一个DF,有几列数据,以秒为单位,例如:600,我想用以下格式将其转换为分钟00:10:00

我已经找到了下面的代码并运行了一些测试,它确实如预期的那样工作,但是,我有几个列,我想更改格式,我正在寻找最有效的方法来运行代码,而不必为每个列创建函数

提前谢谢

def format_duration(row):
      seconds = row.Default_Misc  ## changed this
      minutes, seconds = divmod(seconds, 60)
      hours, minutes = divmod(minutes, 60)
      return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)


aux['Default_Misc'] = aux.apply(format_duration, axis=1)
aux.to_csv(folder_path / 'Report.csv', index=False, encoding='UTF-8')
同样,目前我可以将该函数应用于列['Default_Misc'],但是,还有更多的列需要更改格式。

尝试以下操作:

# sample data
np.random.seed(1)
df = pd.DataFrame({'sec': np.random.randint(200,500, 5)})

# format:
df['sec'].astype('datetime64[s]').dt.strftime("%H:%M:%S")
输出:

0    00:03:57
1    00:07:15
2    00:04:32
3    00:07:35
4    00:06:43
Name: sec, dtype: object
如果要更新数据,请执行以下操作:

df['sec'] = df['sec'].astype('datetime64[s]').dt.strftime("%H:%M:%S")

您可以将其设置为timedelta,并告诉它您的列为秒。

更长、更麻烦的版本:

def timeFormat(seconds, format):
    dt = str(datetime.timedelta(seconds=seconds))
    return (datetime.datetime.strptime(dt, '%H:%M:%S')).strftime(format)

fr = pd.DataFrame({'Datetimes':[600, 1200, 3600]})
fr = fr.Datetimes.apply(timeFormat, format='%H:%M:%S')

这就是我想要的,我能够创建一个函数来迭代所有列并更改格式。。。非常感谢。事实上,我的解决方案只工作了不到24小时。你应该选择@BenPap的答案
def timeFormat(seconds, format):
    dt = str(datetime.timedelta(seconds=seconds))
    return (datetime.datetime.strptime(dt, '%H:%M:%S')).strftime(format)

fr = pd.DataFrame({'Datetimes':[600, 1200, 3600]})
fr = fr.Datetimes.apply(timeFormat, format='%H:%M:%S')