gpt4 book ai didi

python - 将函数应用于 pandas 数据帧的每一列而不使用 for 循环?

转载 作者:行者123 更新时间:2023-12-01 01:47:18 24 4
gpt4 key购买 nike

我想将时间增量的数据帧转换为小时。我可以对一个系列(数据框的一列)执行此操作,但我想找到一种将其应用于所有列的方法。

for 循环 可以工作,但是有没有更快或更Pythonic 的方法来做到这一点?

import pandas as pd 
import datetime
import numpy as np


df = pd.DataFrame({'a': pd.to_timedelta(['0 days 00:00:08','0 days 05:05:00', '0 days 01:01:57']),
'b' : pd.to_timedelta(['0 days 00:44:00','0 days 00:15:00','0 days 01:02:00']),
'c': pd.to_timedelta(['0 days 00:34:33','0 days 04:04:00','0 days 01:31:58'])})

df

a b c
0 00:00:08 00:44:00 00:34:33
1 05:05:00 00:15:00 04:04:00
2 01:01:57 01:02:00 01:31:58

for c in df.columns:
df[c] = (df[c]/np.timedelta64(1,'h')).astype(float)

df

a b c
0 0.002222 0.733333 0.575833
1 5.083333 0.250000 4.066667
2 1.032500 1.033333 1.532778

我尝试过使用 lambda,但有一些错误:

df = df.apply(lambda x: x/np.timedeltat(1, 'h')).astype(float)

返回错误:

AttributeError: ("'module' object has no attribute 'timedelta'", u'occurred at index a')

最佳答案

使用np.timedelta64将所有列转换为二维numpy数组:

df = pd.DataFrame(df.values / np.timedelta64(1, 'h'), columns=df.columns, index=df.index)
print (df)
a b c
0 0.002222 0.733333 0.575833
1 5.083333 0.250000 4.066667
2 1.032500 1.033333 1.532778

如果想使用申请:

df = df.apply(lambda x: x/np.timedelta64(1, 'h'))
print (df)
a b c
0 0.002222 0.733333 0.575833
1 5.083333 0.250000 4.066667
2 1.032500 1.033333 1.532778

或者total_seconds :

df = df.apply(lambda x: x.dt.total_seconds() / 3600)
print (df)
a b c
0 0.002222 0.733333 0.575833
1 5.083333 0.250000 4.066667
2 1.032500 1.033333 1.532778

关于python - 将函数应用于 pandas 数据帧的每一列而不使用 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51151816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com