当前位置: 代码迷 >> python >> 循环和更新大型pandas数据帧中的行的最有效方法
  详细解决方案

循环和更新大型pandas数据帧中的行的最有效方法

热度:86   发布时间:2023-06-19 09:33:29.0

这是我更新数据帧行的代码:

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"
}

我相信这里有可能使用:

#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')
  相关解决方案