在一个大型的 Pandas 数据框中,循环遍历并更新行的最有效方法是什么?

3
这是我用来更新dataframe行的代码片段:
def arrangeData(df):
hour_from_timestamp_list = []
date_from_timestamp_list = []
for row in df.itertuples():
    timestamp = row.timestamp
    hour_from_timestamp = datetime.fromtimestamp(
        int(timestamp) / 1000).strftime('%H:%M:%S')
    date_from_timestamp = datetime.fromtimestamp(
        int(timestamp) / 1000).strftime('%d-%m-%Y')
    hour_from_timestamp_list.append(hour_from_timestamp)
    date_from_timestamp_list.append(date_from_timestamp)
df['Time'] = hour_from_timestamp_list
df['Hour'] = pd.to_datetime(df['Time']).dt.hour
df['ChatDate'] = date_from_timestamp_list
return df

我正在尝试从时间戳中提取时间、小时和聊天日期。代码能够正常运行,但是当有大量数据时,约300,000行左右,该函数的执行速度非常缓慢。有人能提供更好的方法来加快执行速度吗?

对于循环,我已经尝试了iterrows(),但它更加缓慢。

这是我处理的文档:

{
"_id" : ObjectId("5b9feadc32214d2b504ea6e1"),
"id" : 34176,
"timestamp" : NumberLong(1535019434998),
"platform" : "Email",
"sessionId" : LUUID("08a5caac-baa3-11e8-a508-106530216ef0"),
"intentStatus" : "NotHandled",
"botId" : "tony"
}

你能添加一些数据样本吗? - jezrael
@jezrael已经编辑了问题,并提供了数据样本。 - Tony Mathew
1个回答

2

我相信这里可以使用:

#thanks @Chris A for another solution
t = pd.to_datetime(df['timestamp'], unit='ms')

t = pd.to_datetime(df['timestamp'].astype(int) / 1000)
#alternative
#t = pd.to_datetime(df['timestamp'].apply(int) / 1000)
#t = pd.to_datetime([int(x) / 1000 for x in df['timestamp']] )

df['Time'] = t.dt.strftime('%H:%M:%S')
df['Hour'] = t.dt.hour
df['ChatDate'] = t.dt.strftime('%d-%m-%Y')

@jezrael,你的代码运行良好,而且比循环更快。不过还有一件事,我得到的时间戳是格林威治标准时间,如何将其转换为我的本地时间GMT +05:30?有什么办法可以做到这一点吗? - Tony Mathew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接